使用HttpClient类访问Delicious API时,我遇到了一些问题.我有以下代码:
try
{
const string uriSources = "https://api.del.icio.us/v1/tags/bundles/all?private={myKey}";
using (var handler = new HttpClientHandler { Credentials = new
NetworkCredential("MyUSER", "MyPASS") })
{
using (var client = new HttpClient(handler))
{
var result = await client.GetStringAsync(uriSources);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "ERROR...", MessageBoxButton.OK);
}
Run Code Online (Sandbox Code Playgroud)
运行上面的代码时,我得到以下内容:响应状态代码不表示成功:401(未授权).
那么,我怎么能得到这个工作?可能吗?
提前致谢
问候!
c# windows-phone-7 dotnet-httpclient windows-phone-8 asynchttpclient
我想通过WebView调用一个特定的URL .该页面只能在用户登录后调用.我使用AsyncHttpClient库执行登录调用.成功登录后,通过WebView加载URL 似乎无法识别正确的标头esp cookie.我怀疑是在HttpClient和WebView的HttpClient之间cookie没有正确同步.知道为什么吗?.这是我如何使用WebView
final WebView webView = (WebView) content.findViewById(R.id.web_travel_advisory);
String url = "http://mydomainurl.com/get_data_after_login";
webView.setWebViewClient(new WebViewClient());
CookieSyncManager.createInstance(getActivity());
CookieSyncManager.getInstance().startSync();
CookieManager.getInstance().setAcceptCookie(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
Run Code Online (Sandbox Code Playgroud)
感谢你的帮助.
我正在尝试使用Web API中的System.Net.Http.HttpClient调用PostAsync方法.我收到以下错误:
System.AggregateException"任务已取消."
任务:
Id = 1,Status = System.Threading.Tasks.TaskStatus.Canceled,Method ="{null}",Result ="{Not yet computed}"
码:
using (HttpClientHandler handler = new HttpClientHandler())
{
handler.Credentials = new NetworkCredential("MyUsername", "p@ssw0rd");
using (HttpClient client = new HttpClient(handler))
{
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("status", "Hello world"));
HttpContent content = new FormUrlEncodedContent(postData);
var responseTask = client.PostAsync(url, content).ContinueWith(
(postTask) =>
{
postTask.Result.EnsureSuccessStatusCode();
});
}
Run Code Online (Sandbox Code Playgroud)
我假设responseTask会强制该方法同步运行?
它是一个WPF应用程序,而不是ASP.NET.
我正在为大负载(~1M HTTP请求)评估AsyncHttpClient.对于每个请求,我想使用AsyncCompletionHandler调用一个回调,它只会将结果插入阻塞队列
我的问题是:如果我在紧密循环中发送异步请求,AsyncHttpClient将使用多少个线程?(我知道你可以设置最大值,但显然你冒了丢失请求的风险,我在这里看到了)
我目前正在使用这些版本的Netty实现:
如果在以后的版本中有任何优化,我不介意使用其他版本
编辑:
我读到Netty使用reactor模式来响应HTTP响应,这意味着它分配了很少的线程来充当选择器.这也意味着分配的线程数不会随着请求量的增加而增加.但是,这与设置最大连接数的需要相矛盾.
谁能解释我错过的东西?
提前致谢
在Async Http Client文档中,我看到如何获取Future<Response>异步HTTP Get请求的结果,例如:
AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient();
Future<Response> f = asyncHttpClient
.prepareGet("http://api.football-data.org/v1/soccerseasons/398")
.execute();
Response r = f.get();
Run Code Online (Sandbox Code Playgroud)
但是,为方便起见,我希望得到一个CompletableFuture<T>替代方案,我可以应用一个将结果转换为其他内容的延续,例如将响应内容从Json反序列化为Java对象(例如SoccerSeason.java).这就是我想做的事情:
AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient();
CompletableFuture<Response> f = asyncHttpClient
.prepareGet("http://api.football-data.org/v1/soccerseasons/398")
.execute();
f
.thenApply(r -> gson.fromJson(r.getResponseBody(), SoccerSeason.class))
.thenAccept(System.out::println);
Run Code Online (Sandbox Code Playgroud)
根据Async Http Client文档,执行此操作的唯一方法是通过AsyncCompletionHandler<T>对象和使用promise.所以我为此构建了一个辅助方法:
CompletableFuture<Response> getDataAsync(String path){
CompletableFuture<Response> promise = new CompletableFuture<>();
asyncHttpClient
.prepareGet(path)
.execute(new AsyncCompletionHandler<Response>() {
@Override
public Response onCompleted(Response response) throws Exception {
promise.complete(response);
return response;
}
@Override …Run Code Online (Sandbox Code Playgroud) 我试图理解之间的区别:
setRequestTimeout- 设置AsyncHttpClient等待响应完成之前的最长时间(以毫秒为单位).
setReadTimeout- 设置AsyncHttpClient可以保持空闲的最长时间(以毫秒为单位).
我什么时候应该使用一个?
它们如何与一个好老相关java.net.SocketTimeoutException: Read timed out?
我正在构建AsyncHttpClient这样的:
public AsyncHttpClient getAsyncHttpClient() {
AsyncHttpClientConfig config = new AsyncHttpClientConfig.Builder()
.setProxyServer(makeProxyServer())
.setRequestTimeoutInMs((int) Duration.create(ASYNC_HTTP_REQUEST_TIMEOUT_MIN, TimeUnit.MINUTES).toMillis())
.build();
return new AsyncHttpClient(new NettyAsyncHttpProvider(config), config);
}
Run Code Online (Sandbox Code Playgroud)
这在启动时被调用一次,然后返回值传递并在各个地方使用.makeProxyServer()是我自己的函数,让我的代理设置返回一个ProxyServer对象.我需要做的是能够更改代理服务器设置,然后重新创建AsyncHttpClient对象.但是,我不知道如何干净地关闭它.一点点搜索让我相信这close()不是优雅的.我担心每次代理设置更改时都会启动一个新的执行程序和一组线程.这不会经常发生,但我的应用程序运行时很长.
我知道我可以RequestBuilder.setProxyServer()用于每个请求,但是我希望将它设置在一个位置,以便我的asyncHttpClient实例的所有调用者都遵循系统范围的代理设置,而不需要每个开发人员都记住这样做.
什么是重新配置或拆卸和重建Netty基于什么的正确方法AsyncHttpClient?
我是Apache http客户端的新手,我正试图从网站获取状态代码.在Apache http教程中找到以下示例.
import java.util.concurrent.CountDownLatch;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
public class Abc {
static long d2;
public static void main(final String[] args) throws Exception {
d2=System.currentTimeMillis();
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(3000)
.setConnectTimeout(3000).build();
CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom()
.setDefaultRequestConfig(requestConfig)
.build();
try {
httpclient.start();
final HttpGet[] requests = new HttpGet[] {
new HttpGet("http://192.168.26.175:8080/examples/eye/abc10000.jsp")
};
final CountDownLatch latch = new CountDownLatch(1);
for (int v=0;v<1000;v++) {
httpclient.execute(requests[0], new FutureCallback<HttpResponse>() {
public void completed(final HttpResponse response) {
latch.countDown(); …Run Code Online (Sandbox Code Playgroud) 使用AsyncHttpClientwith Netty提供程序将阻止主程序在执行异步请求时终止.例如,下面的程序后终止println,或没有,这取决于供应商是否JDKAsyncHttpProvider还是NettyAsyncHttpProvider:
public class Program {
public static CompletableFuture<Response> getDataAsync(String uri) {
final AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
final CompletableFuture<Response> promise = new CompletableFuture<>();
asyncHttpClient
.prepareGet(uri)
.execute(new AsyncCompletionHandler<Response>(){
@Override
public Response onCompleted(Response resp) throws Exception {
promise.complete(resp);
asyncHttpClient.close(); // ??? Is this correct ????
return resp;
}
});
return promise;
}
public static void main(String [] args) throws Exception {
final String uri = "…";
System.out.println(getDataAsync(uri).get());
}
}
Run Code Online (Sandbox Code Playgroud)
关于AsynHttpClient文档说明: …
我有一个方法,它调用另一个方法,结果并不重要。确切地说,它是对 Web 服务的 POST 请求,结果在该方法中而不是在调用方法中处理。现在我希望 main 方法在该任务完成之前返回。
本质上,我需要某种异步性。我可以在 Java 中使用哪些工具?下面是步骤:
A调用方法BB开始执行(我们对方法 b 的结果不感兴趣:它调用 Web 服务并自行处理结果)A在方法B完成之前返回asynchttpclient ×10
java ×5
asynchronous ×3
netty ×3
c# ×2
android ×1
apache ×1
cookies ×1
http ×1
httpclient ×1
java-8 ×1
wcf-web-api ×1
webview ×1