测试一个调用Post接口的工具类HttpClient

package org.example;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

public class TestHttpClient {
    public static void main(String[] args) {
        Properties properties = new Properties();
        properties.setProperty("test1","jack-sam-0012");       /*数据的样式是这样的*/
        properties.setProperty("esb.url","https://service.cifi.com.cn/auroral/dataLakeLog/insert");  /*原始数据是这样的*/
        properties.setProperty("esb.username","datalake01");   /*原始数据是这样的*/
        properties.setProperty("esb.passwd","wtf");            /*原始数据是这样的 prod@datalake#2021061614150701# 但是我不想连上*/

        properties.setProperty("test2","whatsthematter");
        insertLog(properties,"test1","20210202","20210404",0,10);
    }

    /*下面得到的param为(其中的operationName经过了encoding,就是为了处理特殊字符比如某人的名字就是“&”)
        provider=jack&operationName=sam%E5%85%A5%E6%B9%96&operationCode=0012&beginDate=20210202&endDate=20210404&status=0&dataCount=10
     */
    public static void insertLog(Properties properties,String tablename,String beginDate,String endDate,int status,long dataCount) {
        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        DefaultHttpClient httpClient = new DefaultHttpClient();
        // 参数
        StringBuilder params = new StringBuilder();
        System.out.println("firstStep:传入的properties为===>"+properties);
        /*传入property为
        * {esb.passwd=wtf, esb.username=datalake01, test2=whatsthematter, test1=jack-sam-0012, esb.url=https://service.cifi.com.cn/auroral/dataLakeLog/insert}
        * */
        System.out.println("secondStep:传入的properties匹配上传入的table获取value值===>"+properties.getProperty(tablename));
        /*传入的 properties.getProperty(tablename)为
        *jack-sam-0012
        * */
        try {
            String[] tableInfo = properties.getProperty(tablename).split("-");
                System.out.println("thirdStep:表的数组为===>"+tableInfo);
            // 字符数据最好encoding以下;这样一来,某些特殊字符才能传过去(如:某人的名字就是“&”,不encoding的话,传不过去)
                System.out.println("4thStep:最初的params为===>"+params);
            params.append("provider=").append(tableInfo[0]);
                System.out.println("5thStep:添加后的params为===>"+params);
            params.append("&");
                System.out.println("6thStep:添加后的params为===>"+params);
            params.append("operationName=").append(URLEncoder.encode(tableInfo[1]+"入湖", "utf-8"));
                System.out.println("7thStep:添加后的params为===>"+params);
            params.append("&");
            params.append("operationCode=").append(tableInfo[2]);
            params.append("&");
            params.append("beginDate=").append(URLEncoder.encode(beginDate,"utf-8"));
            params.append("&");
            params.append("endDate=").append(URLEncoder.encode(endDate,"utf-8"));
            params.append("&");
            params.append("status=").append(status);
            params.append("&");
            params.append("dataCount=").append(dataCount);
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        System.out.println(params);
        // 创建Post请求
        System.out.println("查看Post之前的Property===>"+properties.getProperty("esb.url"));
        HttpPost httpPost = new HttpPost(properties.getProperty("esb.url") + "?" + params);
        System.out.println("获取得到的httpPost为==>"+httpPost);
        /*上面获取到的数据示例为
        * POST https://service.cifi.com.cn/auroral/dataLakeLog/insert?provider=jack&operationName=sam%E5%85%A5%E6%B9%96&operationCode=0012&beginDate=20210202&endDate=20210404&status=0&dataCount=10 HTTP/1.1
        * */
        httpPost.addHeader("Authorization", "Basic " + Base64.getUrlEncoder().encodeToString((properties.getProperty("esb.username") + ":" + properties.getProperty("esb.passwd")).getBytes()));
        System.out.println("获取到的新httpPost为==>"+httpPost);

        // 设置ContentType(注:如果只是传普通参数的话,ContentType不一定非要用application/json)
        httpPost.setHeader("Content-Type", "application/json;charset=utf8");
        /*上面获取的数据示例
        * POST https://service.cifi.com.cn/auroral/dataLakeLog/insert?provider=jack&operationName=sam%E5%85%A5%E6%B9%96&operationCode=0012&beginDate=20210202&endDate=20210404&status=0&dataCount=10 HTTP/1.1
        * */

        // 响应模型
        HttpResponse response = null;
        try {
            // 由客户端执行(发送)Post请求   /*返回状态码401  要求身份验证*/
            response = httpClient.execute(httpPost);
            System.out.println("发送Post请求以后获得的===>"+response);
            /*获得的数据示例
            * HTTP/1.1 401  [Content-Type: application/json; charset=UTF-8, Content-Length: 134, Connection: keep-alive, WWW-Authenticate: Basic realm="mule-realm", Date: Tue, 24 Aug 2021 07:59:34 GMT, X-Kong-Upstream-Latency: 8, X-Kong-Proxy-Latency: 0, Via: kong/1.1.2, Set-Cookie: UqZBpD3n3iPIDwJU9Bm6pGiUTv8_=v1MdOvgxScV7i; Expires=Fri, 22-Aug-2031 07:59:35 GMT; Path=/]
            * */
            //从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            System.out.println("获取的相应实体为===>"+responseEntity);
            /*获取的数据示例
            * org.apache.http.conn.BasicManagedEntity@6d3af739*/

            System.out.println("响应状态为:" + response.getStatusLine());
            /*获取的响应状态数据为
            * HTTP/1.1 401
             * */
            if (responseEntity != null) {
                System.out.println("响应内容长度为:" + responseEntity.getContentLength());
                /*134*/
                System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
        /*{"instId":"1629792638594","requestTime":"2021-08-24 16:10:38.038","returnCode":"401","returnMsg":"Bad credentials","returnStatus":"E"}*/
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

HttpClient使用详细示例可以参照下文,包含了调用有参无参get请求和有参无参post请求的示例

httpClient.execute(new HttpGet(xxx))

或者httpClient.execute(new HttpPost(xxx))

https://blog.csdn.net/justry_deng/article/details/81042379

猜你喜欢

转载自blog.csdn.net/someInNeed/article/details/119892759