Java知识点 --- HttpClient简单介绍

   HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。

环境说明:JDK1.8、SpringBoot

第一步:在pom.xml中引入相关jar包

 
     org.apache.httpcomponents
     httpclient
     4.5.3

第二步:1>Get请求的编写

public static String doGetByToken(String url,String tokenKey,String token){

       String rev = "";
       try {
           HttpClient httpClient = new DefaultHttpClient();
           HttpGet httpGet = new HttpGet(url);
           httpGet.addHeader(tokenKey,token);
           httpGet.addHeader("Content-Type", "application/json;charset=utf-8");
	       httpGet.addHeader("User-Agent", "imgfornote");
           HttpResponse response = httpClient.execute(httpGet);
           int code = response.getStatusLine().getStatusCode();
           if (code == 200) {
              rev = EntityUtils.toString(response.getEntity(),Charset.forName("utf-8"));
           }
       } catch(Exception e){
           e.printStackTrace();
           // logger.error("[{}] doGetByToken方法调用异常,异常信息:[{}]", 
           // LocalDateTime.now(), e.getMessage());
       }
      
      return rev;
}

            2>Post请求的编写

public static String doPostByToken(String url, Map params,String 
                        tokenKey,String token) {
        String rev = "";
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader(tokenKey, token);
            httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
            httpPost.addHeader("User-Agent", "imgfornote");
            JSONObject obj = new JSONObject();
            Set> entrySet = params.entrySet();
            Iterator var9 = entrySet.iterator();
            while(var9.hasNext()) {
                Map.Entry entry = (Map.Entry)var9.next();
                obj.put(entry.getKey(), String.valueOf(entry.getValue()));
            }
            StringEntity stringEntity = new StringEntity(obj.toString(), Charset.forName("utf-8"));
            httpPost.setEntity(stringEntity);
            HttpResponse response = httpClient.execute(httpPost);
            int code = response.getStatusLine().getStatusCode();
            if (code == 200) {
              rev = EntityUtils.toString(response.getEntity(), Charset.forName("utf-8"));
            }
        } catch (Exception e) {
            e.printStackTrace();
           // logger.error("[{}] doPostByToken方法调用异常,异常信息:[{}]", 
           // LocalDateTime.now(), e.getMessage());
        }
        return rev;
    }

 

你可能感兴趣的:(Java知识点)