将Json从POJO发送到服务器tomcat

时间:2018-02-24 06:40:11

标签: java json servlets pojo

所以我一直在搜索我的问题扔出互联网,并没有兴奋地满意回答!我正在寻找的是杰克逊或streamoutputwriter的一些功能,将Json发送到我的服务器!我找到了一种从我的服务器获取json的方法

public GetJsonfromServer() {

    try {
        ObjectMapper mapper = new ObjectMapper();

        URL restServiceURL = new URL(targetURL);

        HttpURLConnection httpConnection = (HttpURLConnection) restServiceURL.openConnection();
        httpConnection.setRequestMethod("GET");
        httpConnection.setRequestProperty("Accept", "application/json");

        if (httpConnection.getResponseCode() != 200) {
            throw new RuntimeException(
                    "HTTP GET Request Failed with Error code : " + httpConnection.getResponseCode());
        }
        BufferedReader responseBuffer = new BufferedReader(
                new InputStreamReader((httpConnection.getInputStream())));
        String output = "";

        System.out.println("Output from Server:  \n");
        while ((output = responseBuffer.readLine()) != null) {
            Object s = mapper.readValue(output, Object.class);
            System.out.println(s);
        }
        BufferedWriter requestBuffer = new BufferedWriter(new OutputStreamWriter(httpConnection.getOutputStream()));
        requestBuffer.write("hello from client");
        requestBuffer.flush();

        httpConnection.disconnect();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

这对我来说很好,我可以将我从服务器获取的json转换为对象!我很高兴你帮我找到一种方法用所需的方法将Json发送到服务器(GET,POST,..)!(我在eclipse上使用java)

0 个答案:

没有答案