问题描述
我正在与期望POST参数并期望Request body的Web服务进行通信。我已经确认可以使用我的REST控制台完成这样的POST请求,但是我无法使用Apache库在Java中发出这样的请求。
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.
在下面的代码,我能够POST到Web服务,它正确接收变量raw_body的内容。如果我取消注释两个注释行中的第一行,则Web服务会收到fname参数,但它不再接收POST的正文。
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);
如何传输参数和正文?
推荐答案
您可以使用 setQueryString
方法将参数添加到要发布到的URL。从RESTful的角度来看,我认为你通常不会这样做,但是,因为POST应该表示对资源的调用,并且任何有资格获得查询参数的东西都应该包含在请求中传输的表示中。 body ...或者它应该代表资源本身的资格,在这种情况下,它应该是发布的路径的一部分,然后控制器可以使用@ PathVariable / @ PathParam或类似的东西来提取它。因此,在您的情况下,如果您要保存资源并知道URI,您也可能正在寻找类似 POST /MyRestWebService/files/test.txt
或更合适的PUT。 。服务器上的代码可以从URL模式中提取文件名。
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.
这篇关于如何使用Java进行POST并包含参数和原始请求体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!