Http请求URL中带有json字符串,导致请求406

之前有个需求调用对方的接口,但是由于请求URL中带有json数据,导致406
URL:

https://xxx.xx.com/xx/vip/vipSrfCgi?serviceName=xxxxx&requestBody={"appid":"90089","orderid":"hth123456789","uin":"1635618490","conn_appid":"","time":"1615367453","token":"771e74bfc8a3940b094cecdf37957b80"}&__debugid=1158542577

请求报错:
请求406
查了挺多地方都没有找到,直到有一次在服务器curl才看出猫腻,对json字符串做了处理
处理后:

curl -H 'Content-Type:application/json' -x 10.107.100.64:9090 -X GET "https://xxx.xx.com/xx/vip/vipSrfCgi?serviceName=xxxxx&requestBody=\\{\"appid\":\"108017\",\"orderid\":\"hth123456789\",\"uin\":\"1635618490\",\"time\":\"1615452087\",\"token\":\"a6950569a76f8dc2398451fd2088e825\"\\}&__debugid=1158542577"

(这里我是转义过的,但是贴出来后总是不对,这里要对双引号进行转义)
这里可以看到已经请求成功了,只是返回token错误

因为我是用restTemplate发请求的,我们主要对URL进行处理下:
在这里插入图片描述

public String getForQQString(String url, String request, Class<String> responseType) {
        try {
            URI uri = UriComponentsBuilder.fromUriString(url).build().encode().toUri();
            HttpEntity<String> entity = new HttpEntity<>(request, headers);
            ResponseEntity<String> exchange = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class);
            return exchange.getBody();
        } catch (HttpClientErrorException e) {
            return e.getResponseBodyAsString();
        }
    }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Java发送带有文的JSON请求,您需要确保正确设置请求头和编码。以下是一个示例代码片段,可以使用Java的`HttpURLConnection`类来发送JSON请求: ```java import java.io.*; import java.net.*; public class HttpJsonRequest { public static void main(String[] args) throws Exception { String json = "{\"name\":\"张三\",\"age\":20}"; URL url = new URL("https://example.com/api"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); connection.setDoOutput(true); OutputStream outputStream = connection.getOutputStream(); outputStream.write(json.getBytes("UTF-8")); outputStream.flush(); outputStream.close(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); } } ``` 在上面的示例,我们设置了请求方法为POST,并设置了请求头的Content-Type为“application/json; charset=UTF-8”,以确保文字符正确地编码。我们还打开了输出流,并将JSON字符串作为UTF-8字节数组写入流。最后,我们读取服务器的响应并将其打印出来。 请注意,如果您从其他源获取JSON数据,则需要使用相应的编码。例如,如果您从数据库获取JSON数据,则应使用数据库的编码。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值