end0tknr's kipple - web写経開発

太宰府天満宮の狛犬って、妙にカワイイ

HttpClient for java ≒ LWP::UserAgent for perl

https://hc.apache.org/httpcomponents-client-ga/
http://search.cpan.org/dist/libwww-perl/
久しぶりにHttpClientを使ったら、ver.4.4まで上がり、APIがかなり変更されていた。
HttpClientって、javaではかなり利用されているHTTPクライアントだと思いっていましたが、使っていた方は面倒だったんでしょうね?

以下、写経

package jp.end0tknr;

import java.io.IOException;
import java.net.URISyntaxException;

import org.apache.http.Header;
import org.apache.http.ParseException;
//HttpClient version 4.4
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpRequest {

    public static void main(String[] args) {
        CloseableHttpClient httpClient = HttpClients.createDefault();

        RequestConfig reqConfig = RequestConfig.custom()
                .setConnectTimeout(1000) //msec 
                .setSocketTimeout(1000)  //msec
                .build();
        
        URIBuilder uriBuilder = new URIBuilder()
        .setScheme("https").setHost("www.google.com")
        .setPath("/search")
        .setParameter("q", "httpclient")
        .setParameter("btnG", "Google Search")
        .setParameter("aq", "f");
        
        HttpGet httpGet;
        try {
            httpGet = new HttpGet(uriBuilder.build());
            httpGet.setConfig(reqConfig);
        } catch (URISyntaxException e) {
            e.printStackTrace();
            return;
        }
        
        CloseableHttpResponse response;
        try {
            response = httpClient.execute(httpGet);
        } catch (ClientProtocolException e ) {
            e.printStackTrace();
            return;
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        
        System.out.println("HTTP RES CODE:"+response.getStatusLine());

        System.out.println("\nHTTP RES HEADER:");
        for(Header header : response.getAllHeaders() ){
            System.out.println(header.getName() + header.getValue());
        }

        if(response.getEntity() == null){
            return;
        }
        
        System.out.println("\nHTTP RES CONTENTS:");
        try {
            System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (ParseException | IOException e) {
            e.printStackTrace();
            return;
        }
        
    }
}