HttpClient 模擬發送Post和Get請求 並用fastjson對返回json字符串數據解析,和HttpClient一些參數方法的deprecated(棄用)的綜合總結


最近在做一個接口調用的時候用到Apache的httpclient時候,發現引入最新版本4.5,DefaultHttpClient等老版本常用的類已經過時了,不推薦使用了;去官網看了一下在4.3之后就拋棄了。

可以參考:

點擊此處詳情 推薦使用 CloseableHttpClient

點擊此處詳情 設置過時參數等類也已經在4.3過后不推薦使用

  DefaultHttpClient --> CloseableHttpClient

HttpClient httpClient=new DefaultHttpClient(); --> CloseableHttpClient httpClient = HttpClients.createDefault();

HttpResponse --> CloseableHttpResponse
HttpResponse httpResponse = httpClient.execute(httpPost); --> CloseableHttpResponse httpResponse = httpClient.execute(httpPost);

Post請求

/**
     * Post方式 得到JSONObject
     *
     * @param paramsHashMap post參數
     * @param url
     * @param encoding 編碼utf-8
     * @return
     */
    public JSONObject getJSONObjectByPost(Map<String, String> paramsHashMap, String url, String encoding) {
        //創建httpClient連接
        CloseableHttpClient httpClient = HttpClients.createDefault();

        JSONObject result = null;
    //json方式
    //JSONObject jsonParam = new JSONObject();
    //jsonParam.put("name", "admin");
    //jsonParam.put("pass", "123456");
    //StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8");
    //解決中文亂碼問題
    //entity.setContentEncoding("UTF-8");
    //entity.setContentType("application/json");
    //httpPost.setEntity(entity);

    //表單方式 List
<NameValuePair> nameValuePairArrayList = new ArrayList<NameValuePair>(); // 將傳過來的參數添加到List<NameValuePair>中 if (paramsHashMap != null && !paramsHashMap.isEmpty()) { //遍歷map for (Map.Entry<String, String> entry : paramsHashMap.entrySet()) { nameValuePairArrayList.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } }
     try { // 利用List<NameValuePair>生成Post請求的實體數據 HttpPost httpPost = new HttpPost(url); // 為HttpPost設置實體數據 UrlEncodedFormEntity 把輸入數據編碼成合適的內容   httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairArrayList, encoding)); // HttpClient 發送Post請求 CloseableHttpResponse httpResponse = httpClient.execute(httpPost); if (httpResponse.getStatusLine().getStatusCode() == 200) { // CloseableHttpResponse HttpEntity httpEntity = httpResponse.getEntity(); if (httpEntity != null) { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(httpEntity.getContent(), "UTF-8"), 10 * 1024); StringBuilder strBuilder = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { strBuilder.append(line); } // 用fastjson的JSON將返回json字符串轉為json對象 result = JSON.parseObject(strBuilder.toString()); } catch (Exception e) { e.printStackTrace(); } finally { if (reader != null) { try { //關閉流 reader.close(); } catch (IOException e) { e.printStackTrace(); } } } } } } catch (Exception e) { e.printStackTrace(); } return result; }

 

Get請求

public JSONObject getJSONObjectByGet(String url){
        JSONObject resultJsonObject=null;
       
        //創建httpClient連接
        CloseableHttpClient httpClient = HttpClients.createDefault();

        StringBuilder urlStringBuilder=new StringBuilder(url);
        StringBuilder entityStringBuilder=new StringBuilder();
        //利用URL生成一個HttpGet請求
        HttpGet httpGet=new HttpGet(urlStringBuilder.toString());
        // HttpClient 發送Post請求
        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse=httpClient.execute(httpGet);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //得到httpResponse的狀態響應碼
        if (httpResponse.getStatusLine().getStatusCode()== HttpStatus.SC_OK) {
            //得到httpResponse的實體數據
            HttpEntity httpEntity=httpResponse.getEntity();
            if (httpEntity!=null) {
                BufferedReader reader=null;
                try {
                    reader=new BufferedReader(new InputStreamReader(httpEntity.getContent(), "UTF-8"), 8*1024);
                    String line=null;
                    while ((line=reader.readLine())!=null) {
                        entityStringBuilder.append(line);
                    }
                    // 從HttpEntity中得到的json String數據轉為json
                    String json=entityStringBuilder.toString();
                    resultJsonObject=JSON.parseObject(json);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        try {
                            //關閉流
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return resultJsonObject;
    }

 

本文結合自己經歷及收集網絡知識綜合個人總結,只為分享技術,方便解決問題,如有侵犯版權信息等,請聯系我!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM