java发起HTTP 请求的多种方式

这篇博客介绍了Java中使用Hutool和HttpClient库发起HTTP请求的不同方式,包括POST、GET、DELETE、PUT请求。同时,展示了如何将对象转换为JSON字符串作为请求参数,并添加请求头。还提供了一个自定义工具类`HttpClientUtil`,用于处理DELETE和PUT请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java发起HTTP 请求的多种方式,常用的类为 cn.hutool.http.HttpUtil

但方式有限,需加工,可根据实际情况进行选择

参数多为json格式字符串,先讲几个对象或者转json字符串的方式

1.对象转json串  

String data = JSONObject.toJSONString(bo);

2.拼接json字符串

String data = JSONObject.toJSONString(new HashMap<Object, Object>(1) {{                                            put("param1", new String[]{"123123"});

                     put("param2",1231);

                     put("param3","dss");

                     put("param4","asdad");

}});

String data = JSONObject.toJSONString(new HashMap<Object, Object>(3) {{

                    put("name", "zhang****");

                    put("user_id", "1101238723826918");

                    put("cards", new JSONObject(new HashMap<String, Object>(2) {{

                                                   put("type", "ID");

                                                   put("id", "32428269134582");

                                         }}

                          ).toJSONString());

}});

开始请求,以cn.hutool.http.*为例

1.post请求,参数1为请求路径,参数2默认为json格式字符串
String result = HttpUtil.post("url","data");

2.get请求,参数为url,可选多参数,设置参数或超时时间等
String result = HttpUtil.get("url");

3.添加请求头headers的的post请求

Map<String,String> headerMap = new HashMap<>();

headerMap.put("Content-Type","application/json");

...............

String result=HttpRequest.post("url").addHeaders(headerMap).body(data).execute().body();

4.delete  put请求为封装的工具类,如下

package ;

import com.aliyun.oss.common.comm.HttpDeleteWithBody;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Base64;

/**
 * @author 
 * @title: HttpClientUtil 处理cn.hutool.http.HttpUtil post get外的其他请求方式  delete put 等
 * @description: TODO
 * @date 
 */
public class HttpClientUtil {

    /**
     * 功能描述: delete
     *
     * @Param: [data, url]
     * @Return: java.lang.String
     */
    public static String doDelete(String url, String data) throws IOException {
        CloseableHttpClient client = null;
        HttpDeleteWithBody httpDelete = null;
        String result = null;
        try {
            client = HttpClients.createDefault();
            httpDelete = new HttpDeleteWithBody(url);

            httpDelete.addHeader("Content-type", "application/json; charset=utf-8");
            httpDelete.setHeader("Accept", "application/json; charset=utf-8");
            httpDelete.setEntity(new StringEntity(data));

            CloseableHttpResponse response = client.execute(httpDelete);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity);
        } catch (Exception e) {
        } finally {
            client.close();
        }
        return result;
    }


    public static String doPut(String urlPath, String data, String charSet, String[] header) {
        String result = null;
        URL url = null;
        HttpURLConnection httpurlconnection = null;
        try {
            url = new URL(urlPath);
            httpurlconnection = (HttpURLConnection) url.openConnection();
            httpurlconnection.setDoInput(true);
            httpurlconnection.setDoOutput(true);
            httpurlconnection.setConnectTimeout(5000);// 设置连接主机超时(单位:毫秒)
            httpurlconnection.setReadTimeout(5000);// 设置从主机读取数据超时(单位:毫秒)

            if (header != null) {
                for (int i = 0; i < header.length; i++) {
                    String[] content = header[i].split(":");
                    httpurlconnection.setRequestProperty(content[0], content[1]);
                }
            }

            httpurlconnection.setRequestMethod("PUT");
            httpurlconnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
//            httpurlconnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            if (StringUtils.isNotBlank(data)) {
                httpurlconnection.getOutputStream().write(data.getBytes("UTF-8"));
            }
            httpurlconnection.getOutputStream().flush();
            httpurlconnection.getOutputStream().close();
            int code = httpurlconnection.getResponseCode();

            if (code == 200) {
                DataInputStream in = new DataInputStream(httpurlconnection.getInputStream());
                int len = in.available();
                byte[] by = new byte[len];
                in.readFully(by);
                if (StringUtils.isNotBlank(charSet)) {
                    result = new String(by, Charset.forName(charSet));
                } else {
                    result = new String(by);
                }
                in.close();
            } else {
                System.out.println("请求地址:" + urlPath + "返回状态异常,异常号为:" + code);
            }
        } catch (Exception e) {
            System.out.println("访问url地址:" + urlPath + "发生异常");
        } finally {
            url = null;
            if (httpurlconnection != null) {
                httpurlconnection.disconnect();
            }
        }
        return result;
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值