请求头中添加参数 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; }