java post 消息体,如何使用Java进行POST并包含参数和原始请求体?

本文档探讨了如何在Java中使用Apache HttpClient库向Web服务发送POST请求,同时包含参数和请求体。示例代码展示了一种方法,其中请求体能够正确传递,但添加参数后,请求体不再被接收。建议使用`setQueryString`方法将参数添加到URL中,或者考虑调整请求结构,如使用PUT请求保存资源并指定URI。

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

I am communicating with a web service that expects a POST parameter and also expect Request body. I have confirmed that such a POST request can be done using a REST Console I have, but I am unable to make such a request in Java using Apache libraries.

In the code below, I am able to POST to the web service, and it correctly receives the contents of the variable raw_body. If I uncomment the first of the two commented lines, the web service receives the "fname" parameter, but it no longer receives the body of the POST.

import org.apache.commons.httpclient.HttpClient;

import org.apache.commons.httpclient.methods.PostMethod;

import org.apache.commons.httpclient.methods.RequestEntity;

...

HttpClient httpClient = new HttpClient();

String urlStr = "http://localhost:8080/MyRestWebService/save";

PostMethod method = new PostMethod(urlStr);

String raw_body = "This is a very long string, much too long to be just another parameter";

RequestEntity re = new StringRequestEntity(raw_body, "text/xml", "UTF-16");

//method.addParameter("fname", "test.txt");

//httpClient.getParams().setParameter("fname", "test.txt");

method.setRequestEntity(re);

How can I transmit both the parameter and the body?

解决方案

You could use the setQueryString method to add the parameters to the URL that is being POSTed to. From a RESTful perspective I'd argue you should normally not be doing that, however, since a POST should represent a call to a resource and anything that would qualify for a query parameter should be included in the representation that is being transferred in the request body...or it should represent qualification of the resource itself in which case it should be part of the path that is posted to which could then be extracted by the controller using @PathVariable/@PathParam or something similar. So in your case you could also be looking for something like POST /MyRestWebService/files/test.txt or more fittingly a PUT if you're saving the resource and know the URI. The code on the server could pull the filename out from a URL pattern.

<think>好的,用户想知道如何用Java通过POST请求以RAW方式传递参数,需要示例。首先,我需要确认用户的问题点在哪里。RAW方式通常指的是在请求体中直接发送原始数据,比如JSON或纯文本,而不是表单编码。用户可能已经了解表单POST,但需要发送非表单数据,比如JSON或者XML。 接下来,我需要回忆Java中常用的HTTP客户端库,比如HttpURLConnection、HttpClient(Apache或Java 11+的HttpClient),或者第三方库如OkHttp。用户可能需要原生的解决方案,所以优先考虑HttpURLConnectionApache HttpClient的例子。 然后,考虑如何设置请求头,特别是Content-Type,因为RAW参数需要指定正确的MIME类型,比如application/json或text/plain。同时,要确保数据正确写入请求体且正确关闭输出流。 还需要检查用户提供的引用资料,看看是否有相关的内容。引用中的[2][3]提到了HttpServletRequest获取JSON数据以及使用HttpClient执行POST请求,这可能示例相关。例如,使用HttpURLConnection的话,需要设置setDoOutput(true),获取输出流写入数据。对于Apache HttpClient,构建一个StringEntity设置内容类型。 另外,用户可能需要知道如何处理响应,比如获取响应码读取返回的数据。在示例中应该包括这些步骤,确保代码的完整性。 还要注意用户可能的错误点,比如忘记设置Content-Type头,或者没有正确关闭连接,导致资源泄漏。在示例中需要正确管理资源,使用try-with-resources来避免这些问题。 最后,生成相关问题,帮助用户扩展知识,比如如何发送JSON数据,或者处理文件上传,这可能RAW方式形成对比,用户可能会有后续的问题。</think>以下是Java使用POST请求以RAW方式传递参数的两种常见实现方式(基于原生APIApache HttpClient): ### 方法1:使用HttpURLConnection(原生API) ```java import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class RawPostExample { public static void main(String[] args) throws Exception { URL url = new URL("https://api.example.com/endpoint"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 设置请求属性 conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); // RAW格式的MIME类型 conn.setDoOutput(true); // 写入原始数据 String rawData = "{\"name\":\"John\",\"age\":30}"; try(OutputStream os = conn.getOutputStream()) { byte[] input = rawData.getBytes("utf-8"); os.write(input, 0, input.length); } // 处理响应 int responseCode = conn.getResponseCode(); System.out.println("Response Code: " + responseCode); } } ``` ### 方法2:使用Apache HttpClient ```java import org.apache.http.client.methods.*; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; public class RawPostHttpClient { public static void main(String[] args) throws Exception { try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpPost post = new HttpPost("https://api.example.com/endpoint"); // 设置RAW参数 StringEntity entity = new StringEntity("{\"key\":\"value\"}"); entity.setContentType("application/json"); post.setEntity(entity); // 执行请求 try (CloseableHttpResponse response = httpClient.execute(post)) { System.out.println("Response Code: " + response.getStatusLine().getStatusCode()); } } } } ``` 关键点说明: 1. **Content-Type设置**:必须明确指定对应格式,如`application/json`、`text/plain`等[^4] 2. **数据编码**:需要确保字符编码一致性(推荐UTF-8) 3. **连接管理**:使用try-with-resources自动关闭连接 4. **错误处理**:建议检查响应码(200/201表示成功)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值