我的 java web 项目中有一个标准的 HttpServlet。我使用 Netbeans。我想在 servlet 内调用 Restfull Web 服务,然后捕获 JSON 之类的响应并填充 JSP。 我尝试在网上查找,但没有找到任何内容。
谢谢
最佳答案
这是 HttpPost 的示例:
try {
HttpPost httpPost = new HttpPost("https://exampleurl/providerexample/api/v1/loansforexample"
);
StringEntity params;
params = new StringEntity("{"
+ "\"clientId\": \"" + "2" + "\","
+ "\"productId\": \"" + "1" + "\","
+ "\"locale\": \"" + "en" + "\"}");
httpPost.addHeader("Content-Type", "text/html"); //or text/plain
httpPost.addHeader("Accept-Encoding", "gzip, deflate, sdch");
httpPost.setEntity(params);
HttpResponse response = client.execute(httpPost);
int statuscode = response.getStatusLine().getStatusCode();
String responseBody = EntityUtils.toString(response.getEntity());
if (statuscode == 200) {
System.out.println(responseBody);
}
if (statuscode != 200) {
System.out.println(responseBody);
// JSONObject obj = new JSONObject(responseBody);
// JSONArray errors = obj.getJSONArray("errors");
// String errorMessage = "";
// if (errors.length() > 0) {
// errorMessage = errors.getJSONObject(0).getString("developerMessage");
}
}
catch (Exception ex) {
ex.printStackTrace();
ex.getMessage();
}
HttpGet 几乎相同。
关于java - 在Servlet内部调用RestFul Web Service,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33688639/