我以这种方式将字符串发布到网络服务器:
private async Task makeRequest(string url, string postData)
{
HttpClient client = null;
HttpResponseMessage response = null;
try
{
client = new HttpClient();
response = await client.PostAsync(url, new StringContent(postData));
response.EnsureSuccessStatusCode();
Debug.WriteLine(response.StatusCode + " " + response.ReasonPhrase);
}
catch (HttpRequestException e)
{
Debug.WriteLine(e.Message);
}
}
Run Code Online (Sandbox Code Playgroud)
但response.EnsureSuccessStatusCode();抛出一个HttpRequestException. e.Message当我对异常进行处理时,它说: Response status code does not indicate success: 500 (Internal Server Error).。
我做错了什么导致出现该错误?我该如何纠正它?
c# internal-server-error dotnet-httpclient windows-phone-8 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完成之前返回上下文:我正在开发一个Spark流工作,使用这个库将数据写入InfluxDB .这是环境.
相关依赖:
"org.apache.spark" %% "spark-core" % "2.1.0" % "provided",
"org.apache.spark" %% "spark-streaming" % "2.1.0" % "provided",
"org.apache.spark" %% "spark-streaming-kafka-0-8" % "2.1.0",
"com.paulgoldbaum" %% "scala-influxdb-client" % "0.5.2" // which uses "org.asynchttpclient" % "async-http-client" % "2.0.24"
Run Code Online (Sandbox Code Playgroud)
一切都在我的本地计算机上编译并运行良好,但是当我将程序集jar提交给Spark集群时,我在驱动程序中收到此错误:
Exception in thread "main" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.spark.deploy.worker.DriverWrapper$.main(DriverWrapper.scala:58)
at org.apache.spark.deploy.worker.DriverWrapper.main(DriverWrapper.scala)
Caused by: java.lang.IllegalAccessError: tried to access field io.netty.handler.ssl.JdkSslContext.SUPPORTED_CIPHERS from class io.netty.handler.ssl.NettySslPackageAccessor
at io.netty.handler.ssl.NettySslPackageAccessor.jdkSupportedCipherSuites(NettySslPackageAccessor.java:24)
at org.asynchttpclient.config.AsyncHttpClientConfigDefaults.defaultEnabledCipherSuites(AsyncHttpClientConfigDefaults.java:85)
at org.asynchttpclient.DefaultAsyncHttpClientConfig$Builder.<init>(DefaultAsyncHttpClientConfig.java:635)
at org.asynchttpclient.DefaultAsyncHttpClient.<init>(DefaultAsyncHttpClient.java:67)
at …Run Code Online (Sandbox Code Playgroud) 我得到的结构基本上可以概括为:
在某些时候,我从akka收到一个错误,它几乎没有告诉我.在asynchttpclient返回一些结果后立即发生此错误.(我可以在这一点上打印日志上的结果,它们是从json等解析的..但akka已经出错了)
即使在调试日志记录级别,我也没有从akka或stacktrace获得可解密的错误消息.
我得到的唯一信息是:
2017-03-24 17:22:55 INFO CompanyRepository:111 - search company with name:"somecompanyname"
2017-03-24 17:22:55 INFO CompanyRepository:73 - [QUERY TIME]: 527ms
[ERROR] [03/24/2017 17:22:55.951] [company-api-system-akka.actor.default-dispatcher-3] [akka.actor.ActorSystemImpl(company-api-system)] Error during processing of request: 'requirement failed'. Completing with 500 Internal Server Error response.
Run Code Online (Sandbox Code Playgroud)
这个错误信息是我唯一得到的.配置的相关部分:
akka {
loglevel = "DEBUG"
# edit -- tested with sl4jlogger with no change
#loggers = ["akka.event.slf4j.Slf4jLogger"]
#logging-filter = "akka.event.slf4j.Slf4jLoggingFilter"
parsing {
max-content-length = 800m
max-chunk-size = 100m
}
server {
server-header = akka-http/${akka.http.version}
idle-timeout = …Run Code Online (Sandbox Code Playgroud) 这是我正在使用的代码
AsyncHttpClient asyncHttpClient = asyncHttpClient();
RequestBuilder builder = new RequestBuilder("PUT");
Request request = builder.setUrl("http://localhost:8080")
.setBody(requestBody)
.build();
asyncHttpClient.executeRequest(request, new AsyncCompletionHandler<Object>() {
@Override
public Object onCompleted(Response response) throws Exception {
System.out.println(response.getStatusCode());
return response;
}
});
Run Code Online (Sandbox Code Playgroud)
代码运行正确并打印出响应,但调试日志不断打印此日志
2018-09-19 10:48:43.465 DEBUG 73969 --- [pool-7-thread-1] oanetty.channel.DefaultChannelPool:条目计数:http://localhost:8080:1
知道为什么在请求完成后会继续打印此日志吗?
I use AsyncHttpClient library for async non blocking requests. My case: write data to a file as it is received over the network.
For download file from remote host and save to file I used default ResponseBodyPartFactory.EAGER and AsynchronousFileChannel so as not to block the netty thread as data arrives. But as my measurements showed, in comparison with LAZY the memory consumption in the Java heap increases many times over.
So I decided to go straight to LAZY, but …
我正在开发一个新的Windows Phone 8应用程序.我正在连接到一个返回有效json数据的webservice.我正在使用longlistselector来显示数据.当我在GetAccountList()中使用字符串json时,这很好用; 但是当从DataServices类接收数据时,我收到错误"无法将类型'System.Threading.Tasks.Task'隐式转换为字符串".不知道出了什么问题.欢迎任何帮助.谢谢!
DataServices.cs
public async static Task<string> GetRequest(string url)
{
HttpClient httpClient = new HttpClient();
await Task.Delay(250);
HttpResponseMessage response = await httpClient.GetAsync(url);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Debug.WriteLine(responseBody);
return await Task.Run(() => responseBody);
}
Run Code Online (Sandbox Code Playgroud)
AccountViewModel.cs
public static List<AccountModel> GetAccountList()
{
string json = DataService.GetRequest(url);
//string json = @"{'accounts': [{'id': 1,'created': '2013-10-03T16:17:13+0200','name': 'account1 - test'},{'id': 2,'created': '2013-10-03T16:18:08+0200','name': 'account2'},{'id': 3,'created': '2013-10-04T13:23:23+0200','name': 'account3'}]}";
List<AccountModel> accountList = new List<AccountModel>();
var deserialized = JsonConvert.DeserializeObject<IDictionary<string, JArray>>(json);
JArray recordList = deserialized["accounts"];
foreach (JObject record …Run Code Online (Sandbox Code Playgroud) 我有一个如下所示的卷曲请求:
curl -i -XPOST 'http://my_url:port/write?db=myDb' -u user:xxxxx --data-binary 'FieldName,host=M.233 value=52.666 timestamp'
Run Code Online (Sandbox Code Playgroud)
我正在尝试使用 HttpClient 发布此请求。我不确定应该如何称呼它。这就是我试图做的:
public async void TestHttpClient()
{
var client = new HttpClient();
var credentials = Encoding.ASCII.GetBytes("user:xxxxx");
var header = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(credentials));
client.DefaultRequestHeaders.Authorization = header;
client.BaseAddress = new Uri("http://my_url:port/write?db=myDb");
var result = await client.PostAsync(..);
}
Run Code Online (Sandbox Code Playgroud)
我应该为 PostAsync() 编写哪些参数?
如何从curl 转换--data-binary为FieldName,host=M.233 value=52.666 timestampHttpClient?
asynchttpclient ×10
java ×5
asynchronous ×3
c# ×3
netty ×2
.net ×1
akka ×1
akka-http ×1
apache ×1
apache-spark ×1
curl ×1
dependencies ×1
json ×1
mvvm ×1
nio ×1
nio2 ×1
scala ×1