packagecom.yxjr.common.utils;importnet.sf.json.JSONObject;importorg.apache.http.HttpResponse;importorg.apache.http.client.HttpClient;importorg.apache.http.client.methods.HttpPost;importorg.apache.http.entity.StringEntity;importorg.apache.http.impl.client.DefaultHttpClient;importorg.apache.http.util.EntityUtils;importjava.io.UnsupportedEncodingException;importjava.util.Map;public classHttpClientUtil {//post提交调用方法
public static String callHttpPost(String hostIP, int port, String actionName, MapparamsMap)throwsUnsupportedEncodingException {
JSONObject resultJSon= newJSONObject();
String callbackResult= "";
System.err.println("请求参数是: IP" + hostIP + " actionName:" + actionName + " params:" +paramsMap);
HttpClient httpClient= newDefaultHttpClient();
StringBuilder url= new StringBuilder("http://");if (hostIP != null && !"".equals(hostIP) && !"".equals(actionName) && actionName != null) {
url.append(hostIP).append(":").append(String.valueOf(port)).append("/").append(actionName);
}//if (hostIP != null && !"".equals(hostIP) && !"".equals(actionName) && actionName != null) {//url.append(hostIP).append(":").append(String.valueOf(port)).append("/")//.append(baseUrl).append("/").append(actionName);//}
System.out.println(url);
String str="";if(paramsMap!=null && paramsMap.size()!=0){
str=JSONObject.fromObject(paramsMap).toString();
}
System.err.println("请求参数为:"+str);
HttpPost httpPost= newHttpPost(url.toString());
StringEntity entity= new StringEntity(str, "utf-8");//entity.setContentEncoding("utf-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);try{
HttpResponse response=httpClient.execute(httpPost);int statusCode =response.getStatusLine().getStatusCode();
String entityString=EntityUtils.toString(response.getEntity());
System.err.println("请求返回码为:"+ String.valueOf(statusCode)+" 返回结果为:" +entityString);if(statusCode==200){
callbackResult=entityString;
}else{
resultJSon.put("retCode",-1);
resultJSon.put("retMsg","请求异常,请检查请求内容");
resultJSon.put("resultCode",statusCode);
callbackResult=resultJSon.toString();
}
}catch(Exception e) {
System.err.println("客户端连接异常:"+e.getMessage());
resultJSon.put("retCode",-2);
resultJSon.put("retMsg","连接异常,请检查客户端机服务是否正常开启");
resultJSon.put("resultCode",500);
callbackResult=resultJSon.toString();
e.printStackTrace();
}returncallbackResult;
}
}