java 基於 HttpURLConnection(post)和基於CloseableHttpClient(post) 請求

之前出現過期調用第三方接口,返回數據接收後不到的請情況,使用CloseableHttpClient(post)就好了。



import java.io.*;
import java.net.*;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;



/**
 * HTTP請求工具類
 * @author yedong
 * @date 20181114
 * @version 1.0
 */
public class HttpUtil {
    private static Logger logger = Logger.getLogger(HttpUtil.class);

    /**
     * HttpURLConnection 請求方式
      * @param jsonParam
     * @param urls
     * @return
     */
    public static String getJsonData(JSONObject jsonParam, String urls) {
        StringBuffer sb=new StringBuffer();
        try {
            ;
            // 創建url資源
            URL url = new URL(urls);
            // 建立http連接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 設置允許輸出
            conn.setDoOutput(true);
            // 設置允許輸入
            conn.setDoInput(true);
            // 設置不用緩存
            conn.setUseCaches(false);
            // 設置傳遞方式
            conn.setRequestMethod("POST");
            // 設置維持長連接
            conn.setRequestProperty("Connection", "Keep-Alive");
            // 設置文件字符集:
            conn.setRequestProperty("Charset", "UTF-8");
            // 轉換爲字節數組
            byte[] data = (jsonParam.toString()).getBytes();
            // 設置文件長度
            conn.setRequestProperty("Content-Length", String.valueOf(data.length));
            // 設置文件類型:
            conn.setRequestProperty("contentType", "application/json");
            // 開始連接請求
            conn.connect();
            OutputStream out = new DataOutputStream(conn.getOutputStream()) ;
            // 寫入請求的字符串
            out.write((jsonParam.toString()).getBytes());
            out.flush();
            out.close();

            System.out.println(conn.getResponseCode());

            // 請求返回的狀態
            if (HttpURLConnection.HTTP_OK == conn.getResponseCode()){
                System.out.println("連接成功");
                // 請求返回的數據
                InputStream in1 = conn.getInputStream();
                try {
                    String readLine=new String();
                    BufferedReader responseReader=new BufferedReader(new InputStreamReader(in1,"UTF-8"));
                    while((readLine=responseReader.readLine())!=null){
                        sb.append(readLine).append("\n");
                    }
                    responseReader.close();
                    System.out.println(sb.toString());

                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            } else {
                System.out.println("error++");

            }

        } catch (Exception e) {

        }

        return sb.toString();

    }
    /**
     * 發送post請求 CloseableHttpClient請求方式
     * @param url  路徑
     * @param jsonObject  參數(json類型)
     * @param encoding 編碼格式
     * @return
     * @throws ParseException
     * @throws IOException
     */
    public static String send(String url, JSONObject jsonObject,String encoding) throws ParseException, IOException{
        String body = "";

        //創建httpclient對象
        CloseableHttpClient client = HttpClients.createDefault();
        //創建post方式請求對象
        HttpPost httpPost = new HttpPost(url);

        //裝填參數
        StringEntity s = new StringEntity(jsonObject.toString(), "utf-8");
        s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                "application/json"));
        //設置參數到請求對象中
        httpPost.setEntity(s);
        System.out.println("請求地址:"+url);


        //設置header信息
        //指定報文頭【Content-type】、【User-Agent】
        //httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        //執行請求操作,並拿到結果(同步阻塞)
        CloseableHttpResponse response = client.execute(httpPost);
        //獲取結果實體
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            //按指定編碼轉換結果實體爲String類型
            body = EntityUtils.toString(entity, encoding);
        }
        EntityUtils.consume(entity);
        //釋放鏈接
        response.close();
        return body;
    }



}


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章