使用pojo对象和方法帖子请求Web服务

时间:2016-04-16 22:57:00

标签: java web-services rest httpurlconnection javax.ws.rs

我创建了一个安静的网络服务:

@POST
@Path("grd")
@Consumes("application/json")
@Produces("text/plain")
public String guardarDato(PostParams jsonObject) {
/*
 something here
}

PostParams是一个pojo:

public class PostParams {

    private final  Map<String, String> postParamsList;

    public PostParams() {
        postParamsList = new HashMap<>();
    }

    public void addParameter(String name, String value) {
        postParamsList.put(name, value);
    }

    public String getPostParamsList(String name) {
        return postParamsList.get(name);
    }

    public void getPostParamsMap() {
        if (postParamsList.isEmpty()) {
            System.out.println("Parametros vacios");
        } else {
            for (String key : postParamsList.keySet()) {
                System.out.println("Clave: " + key + " -> Valor: " +         postParamsList.get(key));
            }
        }
    }
}

我试图用HttpUrlConnection从android调用这个web服务, 但我的对象在我的网络服务中是空的pojo。

 try {

        URL url = new URL("http://localhost:8080/VfqCh/hgt/opli/grd");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
       // conn.setRequestProperty("Accept", "application/json");

        PostParams postParams = new PostParams();
        postParams.addParameter("h", "51rt3");
        postParams.addParameter("x", "dsfsd8698sdfs");
        postParams.addParameter("ax", "Dairon");
        postParams.addParameter("tf", "D");
        // String input = "{\"qty\":100,\"name\":\"iPad 4\"}";
        Gson gson = new Gson();
        String gString = gson.toJson(postParams, PostParams.class);
        try (OutputStreamWriter printout = new OutputStreamWriter(conn.getOutputStream())) {
            printout.write(gString);
            printout.flush();
        }

        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new RuntimeException("Failed : HTTP error code : "
                    + conn.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(
                (conn.getInputStream())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }

        conn.disconnect();

    } catch (MalformedURLException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }

}

将信息发送到Web服务,但该对象为null。 如果我更改了Web服务中接收的对象类型,如果它有效!:

@POST
@Path("grd")
@Consumes("application/json")
@Produces("text/plain")
public String guardarDato(String jsonObject) {
/*
 something here
}

但我需要在Web服务中收到一个对象!有可能吗?

1 个答案:

答案 0 :(得分:0)

你为HashMap制作了一个POJO,但你可能刚刚使用了Gson已经提供的JsonObject,基本上就像HashMap一样。然后,你toString它,你有一个JSON字符串,你可以发送到服务器。没有必要Gson.toJson并担心它是否正确转换。

您的服务器正在接受由

定义的JSON字符串
@Consumes("application/json")

因此,这应该是方法

public String guardarDato(String jsonObject) {

您需要将Gson添加为服务器的依赖项,然后您应该能够使用类似PostParams params = Gson.fromJson(jsonObject, PostParams.class)的对象获取JSON,假设数据是从客户端正确发送的,但是如上所述之前,您的POJO不会在JsonObject或普通HashMap

之上添加更多功能