HttpClient工具类

HttpClient工具类

maven依赖信息

       <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.9</version>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>

代码具体实现和测试

package com.example.demo;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
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.utils.URIBuilder;
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.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.*;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Map;
/**
 * httpclient工具类
 */
public class HttpClientUtils {
/**
 * 测试方法
*/
  public static void main(String[] args) throws IOException {
        String url = "http://data.chi4rec.com.cn/xfr/toilet/addToiletData";

        String json1 =  "{\n" +
                "    \"loginName\":\"mhqapi\",\n" +
                "    \"loginPassword\":\"123456\"\n" +
                "}";
     String json="{\n" +
        "\t\"temperature\": \"23.00\",\n" +
        "\t\"humidity\": \"89\",\n" +
        "\t\"carbonDioxide\": \"888.20\",\n" +
        "\t\"hydrogenSulfide\": \"0\",\n" +
        "\t\"ammonia\": \"0\",\n" +
        "\t\"water\": 8,\n" +
        "\t\"electric\": 8,\n" +
        "\t\"paper\": 16,\n" +
        "\t\"soap\": 16,\n" +
        "\t\"peopleFlow\": 90,\n" +
        "\t\"groupType\": 0\n" +
        "}";
     String facilityId ="115337";
        String token = "dc794bce-3f14-4735-af85-eb36d4afcde8";
        String postJson = doPostJson(url, json,facilityId,token);
        //String doPostString = doPostString(url, json1);
       // System.out.println(doPostString);
       // JSONObject jsonObject = JSONObject.fromObject(postJson);
        JSONObject jsonObject = JSONObject.parseObject(postJson);
        //  String token = (String)jsonObject.get("data");
        System.out.println(jsonObject);
        Map<String,String> map = new HashMap<>();
        String urlSend ="";
        String host = "http://wuliu.market.alicloudapi.com";
        String path = "/kdi";
        String appCode="233d5f704a8643ba9676b52";
        String orderNo = "611179134601924";
        String company ="";
        map.put("no",orderNo);
        if(!("".equals(company)) || company!=null){
            map.put("company",company);
        }
        if(!("".equals(company)) && company!=null){
             urlSend = host + path + "?no=" + orderNo +"&type="+company;  // 【5】拼接请求链接
        }else{
             urlSend = host + path + "?no=" + orderNo;  // 【5】拼接请求链接
        }

        String postMsg = HttpClientUtils.doGetToWuliu(urlSend,appCode);

    }
    /**
     * get请求 url带参数
     * @param url
     * @return
     */
    public static String doGetUrlContansParam(String url) {
        JSONObject jsonObject = null;
        String result = null;
        //发送get请求
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpGet httpGet = new HttpGet(url);
            CloseableHttpResponse response = httpClient.execute(httpGet);
            try {
                //获取响应实体
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String content = EntityUtils.toString(entity);
                    jsonObject = JSONObject.parseObject(content);
                    result = jsonObject.get("nonce").toString();
                }
            } finally {
                response.close();
            }
        } catch (IOException ioException) {
            ioException.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }  finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * get请求 参数通过map传递
     * @param url
     * @param param
     * @return
     */
        public static String doGet(String url, Map<String, String> param) {
            // 创建Httpclient对象
            CloseableHttpClient httpclient = HttpClients.createDefault();
            String resultString = "";
            CloseableHttpResponse response = null;
            try {
                // 创建uri
                URIBuilder builder = new URIBuilder(url);
                if (param != null) {
                    for (String key : param.keySet()) {
                        builder.addParameter(key, param.get(key));
                    }
                }
                URI uri = builder.build();
                // 创建http GET请求
                HttpGet httpGet = new HttpGet(uri);
                // 执行请求
                response = httpclient.execute(httpGet);
                // 判断返回状态是否为200
                if (response.getStatusLine().getStatusCode() == 200) {
                    resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (response != null) {
                        response.close();
                    }
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return resultString;
        }

    /**
     * Post请求 参数通过map传递
     * @param url
     * @param param
     * @return
     */
        public static String doPost(String url, Map<String, String> param) {
            // 创建Httpclient对象
            CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse response = null;
            String resultString = "";
            try {
                // 创建Http Post请求
                HttpPost httpPost = new HttpPost(url);
                // 创建参数列表
                if (param != null) {
                    List<NameValuePair> paramList = new ArrayList<NameValuePair>();
                    for (String key : param.keySet()) {
                        paramList.add(new BasicNameValuePair(key, param.get(key)));
                    }
                    // 模拟表单
                    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,"utf-8");
                    httpPost.setEntity(entity);
                }
                // 执行http请求
                response = httpClient.execute(httpPost);
                resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    response.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            return resultString;
        }

    /**
     * post请求  参数是一个json字符串
     * @param url
     * @param json
     * @return
     */
    public static String doPostString(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求 并设置请求头参数
            HttpPost httpPost = new HttpPost(url);

            // 创建请求内容参数传递
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }
    /**
     * post请求  参数是json字符串   headerparam 和 token 是请求头参数
     * @param url
     * @param json
     * @param headerparam
     * @param token
     * @return
     */
        public static String doPostJson(String url, String json,String headerparam,String token) {
            // 创建Httpclient对象
            CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse response = null;
            String resultString = "";
            try {
                // 创建Http Post请求
                HttpPost httpPost = new HttpPost(url);
                //并设置请求头参数
                httpPost.setHeader("headerparam",headerparam);
                httpPost.setHeader("token",token);
                //获取请求头参数
                Header[] tokens = httpPost.getHeaders("token");
                // 创建请求内容参数传递
                StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
                httpPost.setEntity(entity);
                // 执行http请求
                response = httpClient.execute(httpPost);
                resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    response.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            return resultString;
        }

    /**
     * 物流信息查询httpclient远程调物流接口通过发送get请求
     * url携带请求参数
     * appCode:阿里云购买物流接口的验证码
     */
public static String doGetToWuliu(String urlSend ,String appCode) throws IOException {
    try {
        StringBuffer sb = new StringBuffer();
        BufferedReader br = null;

        URL url = new URL(urlSend);
        HttpURLConnection httpURLCon = (HttpURLConnection) url.openConnection();
        httpURLCon.setRequestProperty("Authorization", "APPCODE " + appCode);// 格式Authorization:APPCODE (中间是英文空格)
        int httpCode = httpURLCon.getResponseCode();
        if (httpCode == 200) {
           // String json = read(httpURLCon.getInputStream());
            br= new BufferedReader(new InputStreamReader(httpURLCon.getInputStream()));
            String line = null;
            while((line =br.readLine())!=null){
                line =new String(line.getBytes());
                sb.append(line);
            }
            System.out.println("正常请求计费(其他均不计费)");
            System.out.println("获取返回的json:");
          //  System.out.print(json);
            br.close();
            return sb.toString();
        } else {
            Map<String, List<String>> map = httpURLCon.getHeaderFields();
            String error = map.get("X-Ca-Error-Message").get(0);
            if (httpCode == 400 && error.equals("Invalid AppCode `not exists`")) {
                System.out.println("AppCode错误 ");
                return "AppCode错误";
            } else if (httpCode == 400 && error.equals("Invalid Url")) {
                System.out.println("请求的 Method、Path 或者环境错误");
                return "请求的 Method、Path 或者环境错误";
            } else if (httpCode == 400 && error.equals("Invalid Param Location")) {
                System.out.println("参数错误");
                return "参数错误";
            } else if (httpCode == 403 && error.equals("Unauthorized")) {
                System.out.println("服务未被授权(或URL和Path不正确)");
                return "\"服务未被授权(或URL和Path不正确)";
            } else if (httpCode == 403 && error.equals("Quota Exhausted")) {
                System.out.println("套餐包次数用完 ");
                return "套餐包次数用完";
            } else {
                System.out.println("参数名错误 或 其他错误");
                System.out.println(error);
                return "参数名错误 或 其他错误"+error;
            }
        }
    } catch (MalformedURLException e) {
        System.out.println("URL格式错误");
        return "URL格式错误";
    } catch (UnknownHostException e) {
        System.out.println("URL地址错误");
        return "URL地址错误";
    } catch (Exception e) {
        // 打开注释查看详细报错异常信息
        // e.printStackTrace();
    }
    return null;
}

        /*
         * 读取返回结果
         */
        private static String read(InputStream is) throws IOException {
            StringBuffer sb = new StringBuffer();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String line = null;
            while ((line = br.readLine()) != null) {
                line = new String(line.getBytes(), "utf-8");
                sb.append(line);
            }
            br.close();
            return sb.toString();
        }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值