http请求 学习笔记

package com.test.http;


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

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;

public class HttpClienttest {
    public static JSONObject postJson(String reqUrl, String jsonParam) {
        HttpClient htClient = HttpClientBuilder.create().build();
        HttpPost method = new HttpPost(reqUrl);
        // 解决中文乱码问题
        StringEntity entity = new StringEntity(jsonParam, "utf-8");
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        method.setEntity(entity);
        HttpResponse result = null;
        try {
            result = htClient.execute(method);
        } catch (IOException e) {
            //log.error("Http Client调用方法失败");
            e.printStackTrace();
        }
        String resData = null;
        try {
            resData = EntityUtils.toString(result.getEntity());
        } catch (IOException e) {
            //log.error("Http Client转换实体失败");
            e.printStackTrace();
        }
        return JSONObject.parseObject(resData);
    }

    public static String post(String reqUrl, Map<String, String> reqParams) throws Exception {
        if (reqParams == null) {
            reqParams = new HashMap<>(2);
        }
        System.out.println("---------请求地址:" + reqUrl);
        System.out.println("---------请求参数:" + JSON.toJSONString(reqParams));
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(reqUrl);
        try {
            List<NameValuePair> params = new ArrayList<>();
            for (String key : reqParams.keySet()) {
                params.add(new BasicNameValuePair(key, reqParams.get(key)));
            }
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(params, "UTF-8");
            /* 设置参数 */
            post.setEntity(urlEncodedFormEntity);
            HttpResponse response = client.execute(post);
            HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            /* 释放链接 */
            post.releaseConnection();
        }
    }

    public static String get(String reqUrl, Map<String, String> reqParams) {
        System.out.println("---------请求地址:" + reqUrl);
        System.out.println("---------请求参数:" + JSON.toJSONString(reqParams));
        try {
            return execute(reqUrl, reqParams, "GET");
        } catch (Exception e) {
            //log.error("Http Get请求错误");
            e.printStackTrace();
        }
        return null;
    }

    private static String execute(String reqUrl, Map<String, String> reqParams, String method) throws Exception {
        return execute(reqUrl, reqParams, method, "application/x-www-form-urlencoded");
    }

    private static String execute(String reqUrl, Map<String, String> reqParams, String method, String contentType)
            throws Exception {
        String response;
        URL serverUrl = new URL(reqUrl);
        HttpURLConnection conn = (HttpURLConnection) serverUrl.openConnection();

        conn.setReadTimeout(10000);
        conn.setRequestMethod(method);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);

        if (reqParams != null && reqParams.size() > 0) {
            conn.setRequestProperty("Cookie", reqParams.get("Cookie") + "");
            reqParams.remove("Cookie");
        }
        conn.setRequestProperty("connection", "keep-alive");
        conn.setRequestProperty("Charsert", "UTF-8");
        conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        conn.setRequestProperty("Content-Type", contentType);
        // 传递参数
        String content = getStringData(reqParams);
        byte[] bypes = content.getBytes();
        conn.getOutputStream().write(bypes);
        conn.connect();

        InputStream is = conn.getInputStream();
        BufferedReader in = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
        StringBuilder buffer = new StringBuilder();
        String line;
        while ((line = in.readLine()) != null) {
            buffer.append(line);
        }
        response = buffer.toString();
        conn.disconnect();
        return response;
    }

    private static String getStringData(Map<String, String> params) {
        StringBuilder content = new StringBuilder();
        List<String> keys = new ArrayList<>(params.keySet());
        Collections.sort(keys);

        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = params.get(key);
            if (value != null) {
                content.append(i == 0 ? "" : "&").append(key).append("=").append(value);
            } else {
                content.append(i == 0 ? "" : "&").append(key).append("=");
            }
        }
        return content.toString();
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值