[英]How to post an object to Jersey Rest Service
I have a Jersey Web Service with the following signature: 我有一个带有以下签名的Jersey Web服务:
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response save(Student a) {...}
I want to make a POST request in my java code using org.apache.http.client.HttpClient and pass a Student object. 我想使用org.apache.http.client.HttpClient在我的Java代码中发出POST请求,并传递一个Student对象。 How can I go about doing this?
我该怎么做呢? I found plenty of examples that post a string as namedvaluepair.
我发现了很多示例,这些示例将字符串发布为namedvaluepair。 But not so clear on how a custom object can be posted.
但是对于如何发布自定义对象还不清楚。 Suggestions?
有什么建议吗? Thanks in advance.
提前致谢。
I use this to dmy test, the body is in JSON format. 我用它来进行dmy测试,主体为JSON格式。 so convert your Student object into JSON data.
因此将您的Student对象转换为JSON数据。
public String post(String url, HashMap<String, String>params, String body) throws Exception {
HttpPost postRequest = new HttpPost(url);
for(String key : params.keySet()){
postRequest.addHeader(key, params.get(key));
}
StringEntity input = new StringEntity(body);
input.setContentType("application/json");
postRequest.setEntity(input);
HttpResponse response = (new DefaultHttpClient()).execute(postRequest);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
String output;
StringBuffer totalOutput = new StringBuffer();
while ((output = br.readLine()) != null) {
totalOutput.append(output);
}
return totalOutput.toString();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.