Я пытаюсь проверить мой Restful webservice, поэтому я создал простой Java-клиент, но, к сожалению, он получает ошибку 400 с сервера.Ошибка 400 в клиенте отдыха
Я также попытался протестировать веб-сервис от Advance REST client
, там я получаю правильный ответ. Поэтому, пожалуйста, дайте мне знать, где ошибка в моем коде клиента клиента.
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-сервис идет как этот
@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();
}
Что API вашего веб-сервиса? Какой запрос он ожидает? –
Я использую реализацию JAX-RS 311 Jersey, и он ожидает, что Json будет использоваться. я также отредактирую вопрос с кодом веб-службы. –