HTTP 請求/響應 設置/獲取 Header參數


 

請求頭中添加參數 putKey  /  響應頭中取數據 getKey:

//調接口工具類:
public String makeCerts(String jsonData,String putKey) throws Exception {
   String url = BASE_URL + "/cert/usage/makeCert.do";
   CloseableHttpClient httpClient = HttpClients.createDefault();
   HttpPost httpPost = new HttpPost(url);
   httpPost.setHeader("Content-Type", "application/json");
   
   httpPost.addHeader("putKey", putKey); //Header添加參數
   
   String getKey ="";
   try {
    StringEntity entity = new StringEntity(jsonData, "UTF-8");
    entity.setContentEncoding("UTF-8");
    entity.setContentType("application/json");
    httpPost.setEntity(entity);
    HttpResponse httpResponse = httpClient.execute(httpPost);
    
    // 連接成功
    if (200 == httpResponse.getStatusLine().getStatusCode()) {
    
     // org.apache.http.Header;
     //獲取響應頭,遍歷 取出參數
     Header[] headers = httpResponse.getAllHeaders();
     for (Header header : headers) {
      if ("getKey".equals(header.getName()))
      //返回 getKey 的值
       return header.getValue();
     }
     
    } else {
     System.out.println("連接失敗");
    }
    
   } catch (Exception e) {
    e.printStackTrace();
   } finally {
    httpPost.releaseConnection(); // 釋放連接
   }
   return getKey;
  }

 

請求頭中添加參數(二):

 //參數可放在Map里:
  Map<String, Object> headers = new HashMap<String, Object>();
        headers.put("AppKey", AppKey);
        
    //調接口工具類:    
    public static String resultPostJsonData(String url, JSONObject jsonObject,Map<String, Object> headers) {
        HttpPost httpPost = new HttpPost(url);
        HttpClient httpClient = HttpClients.createDefault();
        httpPost.setHeader("Content-Type", "application/json");
        
        //迭代Map添加
        Iterator var6 = headers.keySet().iterator();
        while (var6.hasNext()) {
            String key = (String) var6.next();
            System.out.println(key +":"+ headers.get(key));
            httpPost.addHeader(key, headers.get(key) + ""); 
        }

        
        String responseString=null;
        try {
            httpPost.setEntity(
                    new StringEntity(jsonObject.toString(), ContentType.create("application/json", "utf-8")));
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity httpEntity = response.getEntity();
            StatusLine statusLine = response.getStatusLine();
            System.out.println("statusLine: "+statusLine);
            InputStream is = httpEntity.getContent();
            byte[] bytes =StreamHelper.toByteArray(is) ;
            is.close();
            responseString = new String(bytes, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpPost.releaseConnection(); // 釋放連接
        }
        return responseString;
    }        

 


免責聲明!

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



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