今天碰到使用java获取x-www-from-urlencoded格式json数据,以前没用过记录一下。
public String getMsg() {
try {
String postURL = "url地址";
PostMethod postMethod = null;
postMethod = new PostMethod(postURL) ;
postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8") ;
postMethod.setRequestBody("Authorization");
//参数设置,需要注意的就是里边不能传NULL,要传空字符串
NameValuePair[] data = {
//传递参数
new NameValuePair("username","账号"),
new NameValuePair("password","密码")
};
postMethod.setRequestBody(data);
org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
int response = httpClient.executeMethod(postMethod); // 执行POST方法
String result = postMethod.getResponseBodyAsString() ;
return result;
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}