HttpClient use cases

package com.qifeng.config.ygx.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.SneakyThrows;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

importjava.io.IOException;
 Import Classes in java.util *. ;
 Import java.util.concurrent.ExecutionException;
 Import java.util.concurrent.Future; 

/ ** 
 * @author zhao the XIN 
 * @Title: HttpClientUtil 
 * @ProjectName as_configurer 
 * @ the Description: the TODO 
 * @date 2019/9/21 13:51 
 * / 
public  class HttpClientUtil { 

   // synchronized manner get request is a request of an address where such uri: http://www.baidu.com 
   // main can not be omitted http otherwise, the report does not specify protocol error if needed with data places uri? a = sss to form 
    public  void doGet () throws ClientProtocolException, IOException {
        //创建CloseableHttpClient
        HttpClientBuilder builder = HttpClientBuilder.create();
        CloseableHttpClient client = builder.build();
        //执行
        HttpUriRequest httpGet = new HttpGet("uri");
        CloseableHttpResponse response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        if(entity!=null){
            String  entityStr= EntityUtils.toString(entity,"utf-8");
            System.out.println(entityStr);
        }
//        System.out.println (response.toString ()); 
    } 

    // synchronized post request mode: data request by the need to bring
     // 
    // httpPost.setEntity (new new StringEntity ( "Beppe", "UTF-. 8")) ; manner,
     // if data is needed with the form of objects, are transformed into a string format json 
    public  void the doPost () throws ClientProtocolException, IOException { 
        HttpClientBuilder Builder = HttpClientBuilder.create (); 
        CloseableHttpClient Client = builder.build () ; 
        HttpPost HttpPost = new new HttpPost ( "URI" ); 
        httpPost.setEntity ( new new StringEntity ( "Beppe", "UTF-. 8" ));
        CloseableHttpResponse response = client.execute(httpPost);
        HttpEntity entity = response.getEntity();
        if(entity!=null){
            String  entityStr= EntityUtils.toString(entity,"utf-8");
            System.out.println(entityStr);
        }
//        System.out.println(response.toString());
    }

     //异步get请求:
    public void doGetAsyn() throws InterruptedException, ExecutionException {
        CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
        // Open HttpClient 
        httpclient.start ();
         // begin 
        HttpGet HttpGet = new new HttpGet ( "URI" ); 
        Future <the HttpResponse> = httpclient.execute Future (HttpGet, null ); 
        the HttpResponse the httpResponse = Future.get (); 
        the System .out.println (httpResponse.getStatusLine () + "===" + httpGet.getRequestLine ()); 
    } 


    // asynchronous mode request post: wherein service logic may be added in their callback 
    public  static  void doPostAsyn (String URL, String outStr) throws a ParseException, IOException, InterruptedException, {ExecutionException 
        CloseableHttpAsyncClient httpAsyncClient =  HttpAsyncClients.createDefault();
        httpAsyncClient.start();
        HttpPost httpost = new HttpPost(url);
//        httpost.addHeader(HTTP.CONTENT_TYPE, "application/json");
        StringEntity se=new StringEntity(outStr,"UTF-8");
        se.setContentType("application/json");
        se.setContentEncoding(new BasicHeader("Content-Type", "application/json"));
        httpost.setEntity(se);
        Future<HttpResponse> future = httpAsyncClient.execute(httpost,null);
        System.out.println(future.get().toString());
        //String result = EntityUtils.toString(response.getEntity(),"UTF-8");
        //jsonObject = JSONObject.fromObject(result);
    }



    @SneakyThrows
    public static String DoPost(String url, JSONObject params){
        HttpClientBuilder builder = HttpClientBuilder.create();
        CloseableHttpClient client = builder.build();
        HttpPost httpPost= new HttpPost(url);


        List<BasicNameValuePair> list=new ArrayList<>();

        if(params!=null) {
            if(params.get("Content-Type")!=null){
                httpPost.addHeader("Content-Type", params.get("Content-Type").toString());
            }
            if(params.get("UserName")!=null){
                httpPost.addHeader("UserName", params.get("UserName").toString());

            }
            if(params.get("type")!=null){
                JSONObject Json = new JSONObject();
                Json.put("type", params.get("type").toString());
                StringEntity entity = new StringEntity(Json.toString(), ContentType.APPLICATION_JSON);
                httpPost.setEntity(entity);
            }
            if(params.get("stationId")!=null){
                list.add(new BasicNameValuePair("stationId", params.get("stationId").toString()));
            }
        }

        if(params.get("Content-Type")==null) {
            httpPost.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
            httpPost.addHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
        }
        CloseableHttpResponse response = client.execute(httpPost);
        HttpEntity entity = response.getEntity();
        if(entity!=null){
            String  entityStr= EntityUtils.toString(entity,"utf-8");
            return  entityStr;
        }else{
            return null;
        }
    }

}

 

Guess you like

Origin www.cnblogs.com/MagicAsa/p/11597639.html