繁体   English   中英

使用Java在AWS Lambda上调用Web服务

[英]Making calls to web-services on AWS Lambda using Java

我只是想从Java AWS Lambda函数调用外部Web服务。 为此,我无法使org.apache.http客户端正常工作。 我有代码:

public static String get(String get) throws ClientProtocolException, IOException{
    RequestConfig defaultRequestConfig = RequestConfig.custom().setExpectContinueEnabled(true).build();
    HttpGet httpGetRequest = new HttpGet(get);
    RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).setSocketTimeout(5000).setConnectTimeout(5000).setConnectionRequestTimeout(5000).build();
    httpGetRequest.setConfig(requestConfig);

    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    HttpResponse httpResponse = httpClient.execute(httpGetRequest); <<<<<
    HttpEntity entity = httpResponse.getEntity();
    StringBuffer all = new StringBuffer();
    if (entity != null) {
        InputStream inputStream = entity.getContent();
        BufferedReader in = new BufferedReader(new InputStreamReader(new BufferedInputStream(inputStream)));
        String read;
        while ((read = in.readLine()) != null){
            all.append(read);
            all.append("\n");
        }
        httpClient.close();
    }
    return all.toString();
}

部署完成后,它将挂在HttpResponse httpResponse = httpClient.execute(httpGetRequest); <<<<< HttpResponse httpResponse = httpClient.execute(httpGetRequest); <<<<<以上。

我可以通过建立一个Socket连接来证明从lambda函数到Internet的连通性,例如Socket s = new Socket(InetAddress.getByName("bbc.co.uk"), 80); 这样我就可以检索数据

所以问题是,第一个在本地工作但在部署时无法工作的代码片段出了什么问题? 还是有一种从Java中的AWS lambda函数调用Web服务的首选方法(我进行了搜索,但找不到最佳实践)? 如果可以的话,我希望不必使用套接字来手工处理HTTP请求。

请尝试使用Rest Template进行此呼叫。

这里的问题是Apache HttpClient的使用,它是一个大型库。 切换到OkHttp解决了我的问题。

try {
    String url = "baseurl for AWS insatnce +8080/Testing/mailGenration/generate?msg=20;

    logger.log("Building HttpClient......");
    HttpClient client = HttpClientBuilder.create().build();
    HttpGet request = new HttpGet(url);

    HttpResponse response = client.execute(request);
    logger.log("Response Code : " + response.getStatusLine().getStatusCode());
} catch (Exception e) {
    logger.log("Exception in sendhttpclient:" + e);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM