httpclient4.5 使用post方式提交请求

 

 private RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(25000).setConnectTimeout(25000)

.setConnectionRequestTimeout(25000).build();

 

private final String charSet = "UTF-8";

 

public String postString(String url, Map param) throws ClientProtocolException, IOException {

 

CloseableHttpClient httpclient = HttpClients.createDefault();

 

try {

RequestBuilder rb = RequestBuilder.post().setUri(new URI(url));

// 请求参数

if (null != param) {

Iterator> item = param.entrySet().iterator();

while (item.hasNext()) {

Entry it = item.next();

// 编码格式utf-8

rb = rb.addParameter(it.getKey(), it.getValue());

}

}

rb.setConfig(requestConfig);

HttpUriRequest login = rb.build();

 

CloseableHttpResponse response = httpclient.execute(login);

if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {

HttpEntity entitys = response.getEntity();

if (entitys != null) {

return EntityUtils.toString(entitys, charSet);

}

}

 

// 关闭

if (null != response) {

response.close();

}

 

if (null != httpclient) {

httpclient.close();

}

 

} catch (Exception e) {

e.printStackTrace();

}

 

return "";

}

 

 //测试方法

 

public class PayBest {

 

public static void orderCommon(){

 

HttpFilePost post = new HttpFilePost();

String url ="http://localhost:8080/yun/api/best.do";

Map param = new HashMap();

param.put("userId", "1111110978");

param.put("orderList", "17022800915900");

param.put("bpwd", "111222");

param.put("method", "payCommon");

 

try {

String result = post.postString(url, param);

System.out.println(result);

} catch (ClientProtocolException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

 

}

 

 

public static void main(String[] args) {

orderCommon();

}

 

}

 

 

 

你可能感兴趣的:(java)