APIClient.java 1.72 KB
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;
    }
}