如何将对象发布到Jersey Rest Service

时间:2014-04-04 20:03:33

标签: java rest jersey

我有一个带有以下签名的Jersey Web服务:

@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response save(Student a) {...}

我想使用org.apache.http.client.HttpClient在我的java代码中发出POST请求,并传递一个Student对象。我该怎么做呢?我找到了很多将字符串作为namedvaluepair发布的示例。但不清楚如何发布自定义对象。建议?提前谢谢。

1 个答案:

答案 0 :(得分:0)

我用它来进行dmy测试,机身采用JSON格式。所以将您的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();    
}