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();
}