httpclient4.5 submit request using post method

 

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

.setConnectionRequestTimeout(25000).build();

 

private final String charSet = "UTF-8";

 

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

 

CloseableHttpClient httpclient = HttpClients.createDefault();

 

try {

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

// request parameters

if (null != param) {

Iterator<Entry<String, String>> item = param.entrySet().iterator();

while (item.hasNext()) {

Entry<String, String> it = item.next();

// encoding format 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);

}

}

 

// closure

if (null != response) {

response.close();

}

 

if (null != httpclient) {

httpclient.close();

}

 

} catch (Exception e) {

e.printStackTrace ();

}

 

return "";

}

 

 //testing method

 

public class PayBest {

 

public static void orderCommon(){

 

HttpFilePost post = new HttpFilePost();

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

Map<String,String> param = new HashMap<String,String>();

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();

}

 

}

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326611792&siteId=291194637