java http客户端

 原生方式

import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * 客户端工具类
 */
public class HttpClient {

    /**
     * 向指定URL发送POST请求
     *
     * @param url
     * @param heads
     * @param body
     * @return 响应结果
     */
    public static Map<String, Object> sendPost(String url, Map<String, String> heads, Map<String, String> body) {
        PrintWriter out = null;
        BufferedReader in = null;
        String res = "";
        Map<String, Object> value = null;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            if (heads != null) {//设置头信息
                for (Map.Entry<String, String> header : heads.entrySet()) {
                    conn.setRequestProperty(header.getKey(), header.getValue());
                }
            }
            conn.setRequestProperty("Charset", "UTF-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //获取响应头信息

            out = new PrintWriter(conn.getOutputStream());
            // 设置请求属性
            String param = "";
            if (body != null && body.size() > 0) {
                Iterator<String> ite = body.keySet().iterator();
                while (ite.hasNext()) {
                    String key = ite.next();// key
                    String val = body.get(key);
                    param += key + "=" + val + "&";
                }
                param = param.substring(0, param.length() - 1);
            }

            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                res += line;
            }


            Map head = conn.getHeaderFields();

            Set<String> keys = head.keySet();
            JSONObject headData = new JSONObject();
            for (String key : keys) {
                headData.put(key, conn.getHeaderField(key));
            }

            JSONObject jsonObject = JSONObject.parseObject(res, JSONObject.class);
            JSONObject bodyData = new JSONObject();
            bodyData.put(ServerConsts.code, jsonObject.getInteger(ServerConsts.code));
            bodyData.put(ServerConsts.reason, jsonObject.getString(ServerConsts.reason));
            bodyData.put(ServerConsts.result, jsonObject.getString(ServerConsts.result));

            value = new HashMap<>();
            value.put(ServerConsts.head, headData);
            value.put(ServerConsts.body, bodyData);

        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("发送 POST 请求出现异常!" + e.getMessage());
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        return value;
    }

    public static void main(String[] args) {
        Map<String, String> head = new HashMap<>();
        head.put("asd", "asd");
        head.put("asd", "dsa");
        String pathUrl = "http://192.168.241.1:81/v2.0";
        Map<String, String> body = new HashMap<>();
        body.put("asd", "afdffs");
        Map<String, Object> stringMapMap = HttpClient.sendPost(pathUrl, head, body);
        for (Map.Entry<String, Object> stringObjectEntry : stringMapMap.entrySet()) {
            System.out.println(stringObjectEntry.getKey() + "::" + stringObjectEntry.getValue());
        }
    }
}

封装方式 (get与post)

pom.xml坐标

 这里使用了fastjson依赖,使用json作为参数进行数据传输,如果有特殊需求可以不引入fastdfs依赖,修改传输传递的代码即可

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

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

代码

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
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.util.EntityUtils;

import java.io.IOException;
import java.util.Map;


/**
 * http发送工具类
 */
public class HttpUtil {


    public static String sendPost(String url, JSONObject headJson, JSONObject bodyJson) throws Exception {
        CloseableHttpClient client = null;
        String result = null;
        try {
            client = HttpClientBuilder.create().build();
            HttpPost post = new HttpPost(url);//支持get/post与put和delete - > HttpDelete
            if (headJson != null) {//设置请求头
                for (Map.Entry<String, Object> head : headJson.entrySet()) {
                    post.addHeader(head.getKey(), head.getValue().toString());
                }
            }
            StringEntity body = new StringEntity(bodyJson.toJSONString(), "utf-8");//设置请求体
            body.setContentEncoding("UTF-8");
            body.setContentType("application/json");//设置发送的请求体数据为json数据
            post.setEntity(body);
            HttpResponse res = client.execute(post);
            result = EntityUtils.toString(res.getEntity());// 返回json格式:
        } catch (Exception e) {
            throw new Exception(e);
        } finally {
            close(client);
        }
        return result;
    }

    public static String sendGet(String url, JSONObject headJson) throws Exception {
        String result = null;
        CloseableHttpClient client = null;
        try {
            client = HttpClientBuilder.create().build();
            HttpGet get = new HttpGet(url);
            if (headJson != null) {//设置请求头
                for (Map.Entry<String, Object> entry : headJson.entrySet()) {
                    get.addHeader(entry.getKey(), String.valueOf(entry.getValue()));
                }
            }
            HttpResponse res = client.execute(get);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result = EntityUtils.toString(res.getEntity());// 返回json格式:
            }
        } catch (Exception e) {
            throw new Exception(e);
        } finally {
            close(client);
        }
        return result;
    }


    /**
     * 关闭资源
     *
     * @param client
     */
    public static void close(CloseableHttpClient client) {
        if (client != null) {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public static void main(String[] args) throws Exception {
        JSONObject bodyJson = new JSONObject();
        bodyJson.put("key1", "value1");
        bodyJson.put("key2", "value2");
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("key1", "value1");
        jsonObject1.put("key2", "value2");
        jsonObject1.put("key3", "value3");
        bodyJson.put("key3", jsonObject1);
        String resp = HttpUtil.sendPost("http://127.0.0.1:8080", null, bodyJson);
        System.out.println("服务端的响应为: " + resp);
    }
}

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
引用\[1\]中的代码展示了使用Java标准库中的HttpURLConnection类来发起一个简单的HTTP POST请求。该代码通过设置请求方法、设置请求体、获取响应码和响应内容等步骤来完成请求。这种方式使用起来比较繁琐,需要编写较多的模板代码。 引用\[2\]中的代码展示了使用Apache HttpComponents HttpClient来发起HTTP请求。该库支持HTTP1.0和HTTP1.1协议,可以处理加密的HTTPS协议,提供了更丰富的特性。代码中使用HttpPost类来创建POST请求,设置请求参数,执行请求并获取响应内容。 除了Java标准库和Apache HttpComponents HttpClient,还有其他一些HTTP客户端库可供选择,如OkHttpClient和Spring Boot中的WebClient。这些库都提供了更简洁、易用的API来发送HTTP请求,并且支持更多的特性和功能。 综上所述,Java中有多种HTTP客户端库可供选择,开发者可以根据自己的需求和偏好选择合适的库来进行HTTP请求的发送和处理。 #### 引用[.reference_title] - *1* *2* [Duang!Duang!Duang!直击痛点的一款 HTTP 客户端框架(Java),墙裂推荐!](https://blog.csdn.net/qing_gee/article/details/118546820)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [Java中的HTTP客户端工具对比](https://blog.csdn.net/weixin_28758387/article/details/122157239)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小钻风巡山

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值