简体   繁体   中英

Receiving a String from Java server to Client

I have a java client which sends JSON object to the server (REST service). The code works perfect. My current server returns "RESPONSE", but I want to modify my code to return a string from server to client (something like "transfer was OK")- in addition to sending the object from client to server. This is the code I have

Server:

@Path("/w")
public class JSONRESTService {
@POST
@Path("/JSONService")
@Consumes(MediaType.APPLICATION_JSON)
public Response JSONREST(InputStream incomingData) {
    StringBuilder JSONBuilder = new StringBuilder();
    try {
        BufferedReader in = new BufferedReader(new InputStreamReader(incomingData));
        String line = null;
        while ((line = in.readLine()) != null) {
            JSONBuilder.append(line);
        }
    } catch (Exception e) {
        System.out.println("Error Parsing: - ");
    }
    System.out.println("Data Received: " + JSONBuilder.toString());

    // return HTTP response 200 in case of success
    return Response.status(200).entity(JSONBuilder.toString()).build();
}
}

Client:

public class JSONRESTServiceClient {
public static void main(String[] args) {
    String string = "";
    try {

        JSONObject jsonObject = new JSONObject("string");

        // Step2: Now pass JSON File Data to REST Service
        try {
            URL url = new URL("http://localhost:8080/w/JSONService");
            URLConnection connection = url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
            out.write(jsonObject.toString());
            out.close();

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

            while (in.readLine() != null) {
            }
            System.out.println("\nJSON REST Service Invoked Successfully..");
            in.close();
        } catch (Exception e) {
            System.out.println("\nError while calling JSON REST Service");
            System.out.println(e);
        }

        br.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

So in order to return a string from the server to the client- I modified first the method in the server to return a string, and I added this to my client :

 BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
 StringBuffer sb = new StringBuffer("");
 String line="";
 while (in.readLine() != null) {
                sb.append(line);
                break;
            }
  System.out.println("message from server: " + sb.toString());
  in.close();

But my string is empty. What am I doing wrong? How should I modify my server/client to receive a simple string back or even an object? Thanks.

Your code (example):

package com.javacodegeeks.enterprise.rest.javaneturlclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class JavaNetURLRESTFulClient {

    private static final String targetURL = "http://localhost:8080/w/JSONService";

    public static void main(String[] args) {

        try {

            URL targetUrl = new URL(targetURL);

            HttpURLConnection httpConnection = (HttpURLConnection) targetUrl.openConnection();
            httpConnection.setDoOutput(true);
            httpConnection.setRequestMethod("POST");
            httpConnection.setRequestProperty("Content-Type", "application/json");

            String input = "{\"id\":1,\"firstName\":\"Liam\",\"age\":22,\"lastName\":\"Marco\"}";

            OutputStream outputStream = httpConnection.getOutputStream();
            outputStream.write(input.getBytes());
            outputStream.flush();

            if (httpConnection.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP 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) {
                System.out.println(output);
            }

            httpConnection.disconnect();

          } catch (MalformedURLException e) {

            e.printStackTrace();

          } catch (IOException e) {

            e.printStackTrace();

         }

        }    
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM