我只是尝试从我的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); <<<<<
行。
我可以通过设置Socket连接来证明我有从lambda函数到互联网的连接,例如Socket s = new Socket(InetAddress.getByName("bbc.co.uk"), 80);
我可以通过这种方式检索数据。
所以问题是第一个代码片段在本地工作但在部署时没有问题?或者是否有一种从Java调用AWS lambda函数的Web服务的首选方法(我已经进行了搜索但找不到最佳实践)?如果我能提供帮助,我宁愿不用手工制作HTTP请求。
答案 0 :(得分:0)
请尝试使用Rest模板拨打此电话。
答案 1 :(得分:0)
这里的问题是Apache HttpClient的使用,这是一个大型库。切换到OkHttp解决了我的情况。
答案 2 :(得分:-1)
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);
}