[英]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.