HttpURLConnectionとHttpClientの違いと使用

8317 ワード

違います
1、HttpURLConnectionはjavaの標準類で、パッケージを作っていないので、使った方がオリジナルです.
2、HttpClientはオープンソースフレームであり、HTTPにアクセスする要求ヘッダ、パラメータ、コンテンツ体、応答などをカプセル化している.HttpURLConnectionにおける入出力ストリーム動作は、このインターフェースでHttpPostとHttpGetとHttpResonseとに統一されている.このように、操作の煩雑性が低減される.
以下、それぞれHttpURLConnectionとHttpClientがGET、POST要求を実現する例を学習として示します.
(1)HttpURLConnectionがGETを実現する
package com.jingchenyong.test;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class Test_HttpURLConnection_GET
{
    
    public static void main(String[] args) throws Exception
    {
        String urlString="http://15.6.46.35:8080/platform/index.html";
        URL url=new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setRequestProperty("Accept-Charset", "UTF-8");
        conn.setRequestProperty("connection", "keep-Alive");
        conn.setRequestMethod("GET");
        conn.connect();
        
        int code=conn.getResponseCode();
        System.out.println(code);
        //          
        //String  result=IOUtils.toString(conn.getInputStream(),"UTF-8");
        //          
        BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        String result="";
        String tmp="";
        while((tmp=br.readLine())!=null){
            result=result+tmp;
        }
        System.out.println(result);
        //      
         
    }
    
}
(2)HttpURLConnectionがPOSTを実現
package com.jingchenyong.test;

import java.io.BufferedOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class Test_HttpURLConnection_POST
{
    
    public static void main(String[] args)
        throws Exception
    {
        //    
        String urlString = "http://15.6.46.37:9200//henry/henry/_search";
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setRequestProperty("Accept-Charset", "UTF-8");
        conn.setRequestProperty("connection", "keep-Alive");
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.connect();
        String jsonstring = getJOSNString();
        if (StringUtils.isNotBlank(jsonstring))
        {
            /**
             * post     
             */
           /* OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os));
            writer.write(jsonstring);
            writer.flush();
            writer.close();*/
            BufferedOutputStream out = new BufferedOutputStream(conn.getOutputStream());
            out.write(jsonstring.getBytes());
            out.flush();
            out.close();
            
            //            GET  
            String  result=IOUtils.toString(conn.getInputStream(),"UTF-8");
            System.out.println(result);
            
            //        ,    
        }
    }
    
    public static String getJOSNString()
    {
        JSONObject jsonobject = new JSONObject();
        JSONObject jsonobject1 = new JSONObject();
        JSONObject jsonobject2 = new JSONObject();
        jsonobject2.put("name", "jingchenyong");
        jsonobject1.put("match", jsonobject2);
        jsonobject.put("query", jsonobject1);
        String jsonstring = JSON.toJSONString(jsonobject);
        return jsonstring;
    }
}
(3)HttpClientがGETを実現する
package com.jingchenyong.test;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.collections.MapUtils;
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;

public class Test_HttpClient_GET
{
    
    public static void main(String[] args) throws Exception
    {
        String url="http://15.6.46.35:8080/platform/index.html";
        URIBuilder builder = new URIBuilder(url);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        Map map=getMap();
        if(MapUtils.isNotEmpty(map)){
            for(Entry entry:map.entrySet()){
                builder.addParameter(entry.getKey(), String.valueOf(entry.getValue()));
            }
            url=builder.build().toString();
        }
        HttpGet get=new HttpGet(url);
        //       
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(1000).build();
        get.setConfig(requestConfig);
        
        //  GET  
        CloseableHttpResponse response=httpClient.execute(get);
        //     
        System.out.println(response.getStatusLine().getStatusCode());
        //            
        /*
        String result=IOUtils.toString(response.getEntity().getContent());
        System.out.println(result);
        */
        //            
        StringBuilder reMsgBuider = new StringBuilder();
        InputStream in = response.getEntity().getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
        String msg = null;
        //        
        while ((msg = reader.readLine()) != null) {
            reMsgBuider.append(msg);
        }
        String result = reMsgBuider.toString();
        System.out.println(result);
        //      
        
    }
    public static Map getMap(){
        Map map=new HashMap();
        //map.put("name", "jingchenyong");
        //map.put("age", 26);
        return map;
    }
}
(4)HttpClientがPOSTを実現する
package com.jingchenyong.test;

import org.apache.commons.io.IOUtils;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class Test_HttpClient_POST
{
    
    public static void main(String[] args) throws Exception{
        String jsonstring=getJOSNString();
        RequestConfig config = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).build();
        CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(config).build();
        HttpPost post = new HttpPost("http://15.6.46.37:9200//henry/henry/_search");
        //  post 
        post.setEntity(new StringEntity(jsonstring,"UTF-8"));
        CloseableHttpResponse response = client.execute(post);
        System.out.println("    :"+response.getStatusLine().getStatusCode());
        //   
        //System.out.println("      (     ):"+IOUtils.toString(response.getEntity().getContent()));
        //     GET
        //   
        System.out.println("      (     ):"+EntityUtils.toString(response.getEntity(), "UTF-8"));
        
    }
    public static String getJOSNString()
    {
        JSONObject jsonobject = new JSONObject();
        JSONObject jsonobject1 = new JSONObject();
        JSONObject jsonobject2 = new JSONObject();
        jsonobject2.put("name", "jingchenyong");
        jsonobject1.put("match", jsonobject2);
        jsonobject.put("query", jsonobject1);
        String jsonstring = JSON.toJSONString(jsonobject);
        return jsonstring;
    }
}
の性能:
HttpURLConnectionのアクセス速度はHttpClientより速いです.