我正在尝试测试我的Restful webservice,所以我创建了一个简单的核心java客户端,但不幸的是它从服务器获得了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();
}
答案 0 :(得分:0)
也许它不是HTTP POST
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");