Java知識点---HttpClient簡単な紹介

2981 ワード

HttpClientはApache Jakarta Commonの下のサブプロジェクトで、効率的で最新の、機能豊富なHTTPプロトコルをサポートするクライアントプログラミングツールパッケージを提供し、HTTPプロトコルの最新バージョンと提案をサポートします.
環境説明:JDK 1.8、SpringBoot
ステップ1:pom.xmlに関連jarパッケージを導入する
 
     org.apache.httpcomponents
     httpclient
     4.5.3

ステップ2: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;
    }