如何将参数传递给javax.ws.rs.client.WebTarget.Builder Put方法

时间:2018-03-19 10:46:07

标签: json jax-rs

我是Jax-RS和Jersey 2.0的新手。这是我想要做的。

我有一个具有以下属性的资源

id - String name -String 评论 - 字符串数组,我想为此添加新评论

所以我有一个REST web服务方法http://host:port/ / rest / resourceupdate这个webservice的主体必须是一个JSON对象

现在我正在尝试构建客户端代码

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;
import  javax.ws.rs.PUT;
import javax.ws.rs.Consumes;

import org.apache.log4j.Logger;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

    void updateComments (String CommentToUpdate)

    {

        String url = "http://host:port/<appl>/rest/resourceupdate";
        //I am building a JSON object

        JSONObject inputObj = new JSONObject();

        //Add all the Inputs
        inputObj.put("ids", id);
        inputObj.put("name", name);

        //we need add the comments as a List

        JSONObject commentObj = new JSONObject();

        commentObj.put("comment", CommentToUpdate);


        SONArray list = new JSONArray();
        list.add(commentObj); 

        inputObj.put("comment", list);

        Client client = ClientBuilder.newClient()

        WebTarget base = client.target(url);

        //But I am unable to figureout how I can send the above JSON object to the 
        //put method

        Response response = base.request().put();

    }

如何将输入发送到put方法?这方面的任何指示都会有所帮助

1 个答案:

答案 0 :(得分:0)

您可以尝试以下方法:

Response response = base.request().put(Entity.json(inputObj.toJSONString()));