1. 程式人生 > >HttpClientUtil傳送json格式請求

HttpClientUtil傳送json格式請求

package http;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;  
import java.util.Map.Entry;

import net.sf.json.JSONObject;
import util.Base64;

import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HttpEntity;  
import org.apache.http.HttpResponse;  
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;  
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;  
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;



/*
 * 利用HttpClient進行post請求的工具類
 */  
public class HttpClientUtil {  
    
    private static final Logger logger = Logger.getLogger(HttpClientUtil.class);
    
    static{
        try {
            System.setProperty("jsse.enableSNIExtension", "false");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 傳送post請求
     * @param url 請求路徑
     * @param param 請求json資料
     * @return
     */
    public static String doPost(String url,JSONObject param){  
        HttpPost httpPost = null;  
        String result = null;  
        try{  
            HttpClient client =  new SSLClient();
            httpPost = new HttpPost(url);
            if(param != null){
                StringEntity se = new StringEntity(param.toString(),"utf-8");
//                se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json; charset="));
                httpPost.setEntity(se); //post方法中,加入json資料
                httpPost.setHeader("Content-Type","application/json");
            }
            
            HttpResponse response = client.execute(httpPost);
            if(response != null){  
                HttpEntity resEntity = response.getEntity();  
                if(resEntity != null){  
                    result = EntityUtils.toString(resEntity,"utf-8");  
                }  
            }  
            
        }catch(Exception ex){  
            ex.printStackTrace();  
        }  
        System.out.println("返回結果:\n"+result);
        return result;  
    }  
    
    /**
     * 傳送post請求
     * @param url 請求路徑
     * @param jsonparam 請求json資料字串
     * @return
     */
    public static String taikangPost(String url,String jsonparam){  
        HttpPost httpPost = null;  
        String result = null;  
        try{  
            HttpClient client =  new SSLClient();
            httpPost = new HttpPost(url);
            logger.info("請求路徑:\n"+url);
            logger.info("請求引數:\n"+jsonparam);
            if(jsonparam != null){
                jsonparam = Base64.encodeGBK(jsonparam.getBytes("GBK"));
                StringEntity se = new StringEntity(jsonparam,"GBK");
                httpPost.setEntity(se); //post方法中,加入json資料
                httpPost.setHeader("Content-Type","application/text");
            }
            
            HttpResponse response = client.execute(httpPost);
            
            if(response != null){  
                HttpEntity resEntity = response.getEntity();  
                if(resEntity != null){  
                    result = EntityUtils.toString(resEntity,"GBK");
                    logger.info("返回結果原始字串:\n"+result);
                    result = Base64.decode(result,"GBK");
                }  
            }  
            
        }catch(Exception ex){  
            ex.printStackTrace();  
        }  
        logger.info("返回結果:\n"+result);
        return result;  
    }  
    
    
    /**
     * 傳送post請求
     * @param url 請求路徑
     * @param param 請求引數資料
     * @return
     */
    @SuppressWarnings("unchecked")
    public static String doPostMap(String url,Map<String, String> map){  
        HttpClient httpClient = null;  
        HttpPost httpPost = null;  
        String result = null;  
        try{  
            httpClient = new SSLClient();  
            httpPost = new HttpPost(url);  
            //設定引數  
            List<NameValuePair> list = new ArrayList<NameValuePair>();  
            Iterator iterator = map.entrySet().iterator();  
            while(iterator.hasNext()){  
                Entry<String,String> elem = (Entry<String, String>) iterator.next();  
                list.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));  
            }  
            if(list.size() > 0){  
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,"UTF-8");  
                httpPost.setEntity(entity);  
            }  
            HttpResponse response = httpClient.execute(httpPost);  
            if(response != null){  
                HttpEntity resEntity = response.getEntity();  
                if(resEntity != null){  
                    result = EntityUtils.toString(resEntity,"UTF-8");  
                }  
            }  
        }catch(Exception ex){  
            ex.printStackTrace();  
        }  
        logger.info("返回結果"+result);
        return result;  
    }  
    
    /**
     * 傳送get請求
     * @param url 請求路徑
     * @param param 請求json資料
     * @return
     */
    public static String doGet(String url){
         String result = null;  
         try{  
            HttpClient client = new SSLClient();
            //用get方法傳送http請求
            HttpGet get = new HttpGet(url);
            CloseableHttpResponse httpResponse = null;
            //傳送get請求
            httpResponse = (CloseableHttpResponse) client.execute(get);
            try{
                //response實體
                HttpEntity entity = httpResponse.getEntity();
                if (null != entity){
                    result = EntityUtils.toString(entity,"utf-8");
                }
            }
            finally{
                httpResponse.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;  
    }  
    
    public static void main(String[] args) {
        JSONObject obj = new JSONObject();
        obj.element("a", 1);
//        HttpClientUtil.doPost("http://180.168.131.15/cpf/tianan_cpf/access/car/queryCarModel.mvc",obj);
        HttpClientUtil.taikangPost("http://ecuat.tk.cn/tkcoop_zz/service/proposalEntrance/proposalCreateEntrance?sign=ehaitun&comboid=1007A00901&fromId=62667",obj.toString());
    }
    
    
}