我有这段代码:
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import com.google.inject.Inject;
public class GenericHttpClient implements IGenericHttpClient {
private CloseableHttpClient client;
@Inject
@Singleton
public GenericHttpClient() {
// client = HttpClientBuilder.createForBl()
// .setConnectionTimeToLive(1, TimeUnit.MINUTES)
// .build();
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(20 * 1000)
.build();
client = HttpClientBuilder
.create()
.setDefaultRequestConfig(requestConfig)
.build();
}
@Override
public String sendHttpGetRequest(String url) {
// Constants.CONFIG_QUERY_URL
String answer = null;
try {
CloseableHttpResponse response = client.execute(new HttpGet(url));
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
answer = EntityUtils.toString(response.getEntity());
}
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
return answer;
}
}
我怎么知道org.apache.http.client
是否在其API下使用Java NIO或NIO.2?我可以使用另一个库来实现NIO吗?
此外,我对网络的所有工作都是GET
并返回一个带有响应的对象作为对象成员之一。
因此,在NIO之后我的帖子将被Future.get()
阻止。我不确定我当时是在保存任何资源。
//Send the message
Future<Integer> successfullyWritten= asynchronousSocketChannel.write(helloBuffer);
//Do some stuff here. The point here is that asynchronousSocketChannel.write()
//returns almost immediately, not waiting to actually finish writing
//the hello to the channel before returning control to the currently executing thread
doSomethingElse();
//now you can come back and check if it was all written (or not)
System.out.println("Bytes written "+successfullyWritten.get());