APIClient.java
1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.diligrp.website.rpc;
import com.alibaba.fastjson.JSONObject;
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.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import java.util.Map;
public class APIClient {
private static final Logger log=Logger.getLogger(APIClient.class);
public static String postJson(String url, JSONObject params,Map<String,String> header){
return post(url, params.toJSONString(),header);
}
@SuppressWarnings({ "resource", "deprecation" })
public static String post(String url,String params,Map<String,String> header){
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
if (header != null) {
for(String key:header.keySet()){
post.setHeader(key, header.get(key));
}
}
post.setEntity(new StringEntity(params, "UTF-8"));
String res=null;
HttpResponse response=null;
try {
log.info("远程请求:"+url+" 参数:"+params);
response= client.execute(post);
HttpEntity entity=response.getEntity();
res=EntityUtils.toString(entity, "UTF-8");
log.info(res);
} catch (Exception e) {
log.error("远程请求失败:【"+url+"】 参数:"+params+" 响应结果:"+res, e);
JSONObject object=new JSONObject();
object.put("500","操作失败!");
return object.toJSONString();
}
return res;
}
}