Java实现Http的Get请求发送Json格式报文

主函数代码块:

			HttpClient httpClient = HttpClientBuilder.create().build();
            // Get请求
            URIBuilder uriBuilder = new URIBuilder(payurl);
            if (StringUtils.isNotEmpty(reqJson)) {
                List<NameValuePair> nameValuePairList = json2NameValuePairList(JSON.parseObject(reqJson));
                uriBuilder.setParameters(nameValuePairList);
            }
            HttpGet httpGet = new HttpGet(uriBuilder.build());
            // 设置Header
            httpGet.setHeader("Content-Type", "application/json");

            HttpResponse httpResponse = httpClient.execute(httpGet);

公共方法块:

	private List<NameValuePair> json2NameValuePairList(JSONObject params) {
        if (params != null && !params.isEmpty()) {
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                if (entry.getValue() != null) {
                    String value = String.valueOf(entry.getValue());
                    list.add(new BasicNameValuePair(entry.getKey(), value));
                }
            }
            return list;
        }
        return null;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java发送HTTP POST请求并设置报文头的expect参数,可以使用Java内置的HttpURLConnection类。以下是一个示例代码: ```java import java.net.HttpURLConnection; import java.net.URL; import java.io.OutputStream; import java.io.BufferedReader; import java.io.InputStreamReader; public class HttpPostWithExpectHeader { public static void main(String[] args) throws Exception { String url = "http://example.com/api"; String jsonBody = "{\"name\": \"John\", \"age\": 30}"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // 设置HTTP请求方法为POST con.setRequestMethod("POST"); // 设置报文头的expect参数 con.setRequestProperty("Expect", "100-continue"); // 设置请求体 con.setDoOutput(true); OutputStream os = con.getOutputStream(); os.write(jsonBody.getBytes()); os.flush(); os.close(); // 获取响应 int responseCode = con.getResponseCode(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // 输出响应 System.out.println("Response Code : " + responseCode); System.out.println("Response Body : " + response.toString()); } } ``` 在代码中,我们首先建立一个URL对象,然后使用HttpURLConnection打开连接。我们设置HTTP请求方法为POST,并设置报文头的expect参数为"100-continue"。接下来,我们设置请求体并发送请求。最后,我们获取响应并输出响应码和响应体。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值