java post请求怎么自定义header

 看效果

代码如下

package com.hi.hailiaowenan.thirdpart.service.impl;

import org.apache.http.HttpStatus;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import java.util.Map;
import java.util.HashMap;
import com.alibaba.fastjson.JSONObject;
import com.hi.hailiaowenan.thirdpart.service.ChatService;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;

@Service
public class ChatServiceImpl implements ChatService {

    @Override
    public JSONObject completions(String content, String appId) {

        // ============ 接口url ================
        String url = "xxx";

        // ============ 请求body ================
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("model", "gpt-3.5-turbo");
        jsonObject.put("stream", true);
        JSONObject messages = new JSONObject();
        JSONArray array = new JSONArray();
        messages.put("role", "user");
        messages.put("content", content);
        array.add(messages);
        jsonObject.put("messages", array);

        // ============ 添加请求头信息 ================
        Map<String, String> heads = new HashMap<>();
        // 使用json发送请求,下面的是必须的
        heads.put("Content-Type", "application/json");
        heads.put("Authorization", "xxx");

        // ============ 发送请求 ================
        HttpResponse response = HttpRequest.post(url)
                .headerMap(heads, false)
                .body(String.valueOf(jsonObject))
                .timeout(5 * 60 * 1000)
                .execute();
        // ============ 打印结果 ================
        System.out.println("============ \u6253\u5370\u7ED3\u679C ================");
        System.out.println(response);
        // String strResult = EntityUtils.toString(response.body());
        return jsonObject;
    }

}

或者

package com.hi.hailiaowenan.thirdpart.service.impl;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hi.hailiaowenan.thirdpart.service.ChatService;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;

@Service
public class ChatServiceImpl implements ChatService{

    @Override
    public JSONObject completions(String content, String appId) {

        // ============ 接口url ================
        String url = "xx";

        // ============ 请求body ================
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("model", "gpt-3.5-turbo");
        jsonObject.put("stream", true);
        JSONObject messages = new JSONObject();
        JSONArray array = new JSONArray();
        messages.put("role", "user");
        messages.put("content", content);
        array.add(messages);
        jsonObject.put("messages", array);

        // ============ 发送请求 ================
        String result2 = HttpRequest.post(url)
                .header("Content-Type", "application/json")
                .header("Authorization", "xxx")
                .body(String.valueOf(jsonObject))
                .timeout(5 * 60 * 1000)
                .execute().body();
        // ============ 打印结果 ================
        System.out.println("============ \u6253\u5370\u7ED3\u679C ================");
        System.out.println(result2);
        //11.读取输入流中的返回值
        return JSON.parseObject(result2);
    }

}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java发送HTTP POST请求非常常见和简单,可以使用HttpURLConnection或HttpClient来实现。获取返回的请求header也很简单,只需要在发送请求后使用getResponseHeader()或getAllHeaders()方法获取即可。 以HttpURLConnection为例,发送POST请求并获取返回的请求header的代码如下: ``` URL url = new URL("http://www.example.com/api"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); os.write(jsonString.getBytes()); os.flush(); // 获取返回的请求header Map<String, List<String>> headers = conn.getHeaderFields(); for (Map.Entry<String, List<String>> entry : headers.entrySet()) { String key = entry.getKey(); List<String> values = entry.getValue(); System.out.println(key + ": " + values); } BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); os.close(); conn.disconnect(); ``` 上述代码中,首先创建了一个URL和HttpURLConnection对象,然后设置POST请求的Content-Type,将请求体写入输出流中,并发送请求。接着使用conn.getHeaderFields()方法获取返回的请求header并遍历输出。最后读取返回的响应体并关闭连接。 需要注意的是,如果返回的响应头中有多个值,则可以用getList()方法获取并输出。此外,如果需要在请求头中添加自定义header,则可以使用setRequestProperty()方法来实现。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值