0

I am trying to test my Restful webservice , so i made a simple core java client, but unfortunately it is getting a 400 error from the server.

I also tried to test the web-service from the Advance REST client, there i am getting correct response.So, please let me know where is the error in my rest client code.

public void testPostRequestWithJsonPayload() throws IOException {
    String url = "http://localhost:14443/de.vogella.jersey.first/rest/employee/get";
    String charset = "UTF-8";

    URL service = new URL(url);
    URLConnection connection = service.openConnection();
    connection.setDoOutput(true); // Triggers POST.
    connection.setRequestProperty("Accept-Charset", charset);
    connection.setRequestProperty("Content-Type",
            "application/json; charset="+charset);

    OutputStreamWriter wr = new OutputStreamWriter(
            connection.getOutputStream());
    // =============================================
    JSONObject data = new JSONObject();
    data.put("jsonParam", "2");

    wr.write(data.toString());

    connection.connect();
    InputStream stream = connection.getInputStream();
    int c;
    StringBuilder d = new StringBuilder();
    while ((c = stream.read()) != -1) {
        char ch = (char) c;
        d.append(ch);
    }
    System.out.println(d.toString());
}

Web-service goes like this

@POST
@Path("/get")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response getEmplByPostWithJson(JSONObject id) {

    System.out.println("getEmplByPostWithJson");
    EmployeeDAO dbHandler = new EmployeeDAOImpl();
    String value;
    int empId = 0;
    try {
        value = id.getString("jsonParam");
        empId = Integer.parseInt(value);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    Employee fetchedEmployee = dbHandler.findEmployee(empId);

    JSONObject o = new JSONObject();
    try {
        o.put("empName", fetchedEmployee.getEmpName());
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    ResponseBuilder rb = new ResponseBuilderImpl();
    rb.type(MediaType.APPLICATION_JSON);
    rb.entity(o);
    return rb.build();
}

1 Answers1

0

Maybe it is NOT a HTTP POST

  connection = (HttpURLConnection)url.openConnection();
  connection.setRequestMethod("POST");
venergiac
  • 7,469
  • 2
  • 48
  • 70
  • Unfortunately, this is not the correct solution. There is something wrong with Json data that i am sending because similar method i am using for sending form data in post request works fine. So, there must be some issue with Json data within request body. –  Jan 04 '14 at 20:25