记录一下常用的post接口调用方式
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
public class HttpClientUtil {
public static String doPost(String url, String jsonstr, String charset) {
HttpClient httpClient = null;
HttpPost httpPost = null;
String result = null;
try {
httpClient = new SSLClient();
httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
httpPost.setHeader("Accept", "application/json");
StringEntity se = new StringEntity(jsonstr, "utf-8");
se.setContentType("text/json");
se.setContentEncoding(new BasicHeader("Content-Type",
"application/json"));
httpPost.setEntity(se);
// 请求超时
httpClient.getParams().setParameter(
CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
// 读取超时
httpClient.getParams().setParameter(
CoreConnectionPNames.SO_TIMEOUT, 10000);
HttpResponse response = httpClient.execute(httpPost);
if (response != null) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity, charset);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
}
使用方式:
Map<String,String> map=new HashMap<String , String>();
map.put("aa", "111");
String url = "http://127.0.0.1:9090/...";
String res = HttpClientUtil.doPost(url, JSONObject.toJSONString(map), "utf-8");