public static void main(String[] args) throws IOException {
String url = "http://www.baidu.com";
Map<String,String> map = new HashMap<>();
map.put("name","yukai");
map.put("age","14");
HttpClient httpClient = new HttpClient();//创建httpClient实例
httpClient.getParams().setContentCharset("UTF-8");
PostMethod postMethod = new PostMethod(url);//创建PostMethod对象
postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"UTF-8");
//设置超时时间
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
httpClient.getHttpConnectionManager().getParams().setSoTimeout(15000);
NameValuePair[] nvp = new NameValuePair[map.size()];
int i = 0;
for (String keyAndvalue : map.keySet()){//将请求数据,放入到NameValuePair数组中
NameValuePair nameValuePair = new NameValuePair();
nameValuePair.setName(keyAndvalue);
nameValuePair.setValue(map.get(keyAndvalue));
nvp[i] = nameValuePair;
i++;
}
postMethod.setRequestBody(nvp);
postMethod.addParameter("name","name");
httpClient.executeMethod(postMethod);
String response = postMethod.getResponseBodyAsString();//返回结果
int statusCode = postMethod.getStatusCode();//请求code
}
PostMethod请求
最新推荐文章于 2024-07-06 15:08:01 发布