在Servlet中调用RestFull Web服务

时间:2015-11-13 08:36:25

标签: java web-services rest servlets web

我的java web项目中有一个标准的HttpServlet。我使用Netbeans。我想在servlet中调用Restfull Web服务,之后我会像JSON一样捕获响应并填充JSP。 我试图在网上找到但我没有找到任何东西。

谢谢

1 个答案:

答案 0 :(得分:1)

这是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几乎一样。