我需要向Web服务器发送一个POST请求,其中包含一个gzip压缩请求参数.我正在使用Apache HttpClient,我已经读过它支持开箱即用的Gzip,但我找不到任何如何做我需要的例子.如果有人能发布一些这方面的例子,我会很感激.
在我的应用程序中,我想同时处理几个文件的下载.为此,我将启动多个服务,每个请求一个.我不确定,Android是否支持并行的http请求?
在这种情况下,每个请求有一个HTTPClient是好习惯还是坏习惯?
非常感谢您的帮助!
我被要求在C#中执行以下操作:
/**
* 1. Create a MultipartPostMethod
* 2. Construct the web URL to connect to the SDP Server
* 3. Add the filename to be attached as a parameter to the MultipartPostMethod with parameter name "filename"
* 4. Execute the MultipartPostMethod
* 5. Receive and process the response as required
* /
Run Code Online (Sandbox Code Playgroud)
我写了一些没有错误的代码,但是没有附加文件.
有人可以查看我的C#代码,看看我是否错误地编写了代码?
这是我的代码:
var client = new HttpClient();
const string weblinkUrl = "http://testserver.com/attach?";
var method = new MultipartFormDataContent();
const string fileName = "C:\file.txt";
var streamContent = new …Run Code Online (Sandbox Code Playgroud) 我想在我的mvc项目中使用ReadAsAsync()和.net 4.0.结果为null.
如果我输入uri到地址栏,则chrome的结果为(标签名称已更改):
<ns2:MyListResponse xmlns:ns2="blablabla">
<customerSessionId>xxcustomerSessionIdxx</customerSessionId>
<numberOfRecordsRequested>0</numberOfRecordsRequested>
<moreResultsAvailable>false</moreResultsAvailable>
<MyList size="1" activePropertyCount="1">
<MySummary order="0">
<id>1234</id>
<name>...</name>
.
.
</MySummary>
</MyList>
</ns2:MyListResponse>
Run Code Online (Sandbox Code Playgroud)
如果我在代码中使用该语句:
using (var client = new HttpClient())
{
var response = client.GetAsync(apiUri).Result;
var message = response.Content.ReadAsStringAsync().Result;
var result1 = JsonConvert.DeserializeObject<MyListResponse>(message);
var result2 = response.Content.ReadAsAsync<MyListResponse>().Result;
}
Run Code Online (Sandbox Code Playgroud)
消息以字符串格式出现"{\"MyListResponse\":{\"customerSessionId\"...}",对应于json对象:
{"MyListResponse":
{"customerSessionId":"xxcustomerSessionIdxx",
"numberOfRecordsRequested":0,
"moreResultsAvailable":false,
"MyList":
{"@size":"1",
"@activePropertyCount":"1",
"MySummary":
{"@order":"0",
"id":1234,
"name":"...",
.
.
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
并且result1和result2的属性为null或默认值.类定义如下.我想将内容作为对象阅读,但我不能.您有什么建议来解决这个问题?我究竟做错了什么?提前致谢.
public class MySummary
{
public int @Order { get; set; }
public string …Run Code Online (Sandbox Code Playgroud) 我正在使用System.Net.Http的HttpClient使用以下代码使用"POST"调用REST API:
using (HttpRequestMessage requestMessage = new HttpRequestMessage(
HttpMethod.Post, new Uri(request)) { })
{
response = await httpClient.PostAsync(request, objectContent);
}
Run Code Online (Sandbox Code Playgroud)
"objectContent"目前是这个 -
objectContent = new ObjectContent(jsonContent.GetType(),
jsonContent,
new JsonMediaTypeFormatter());
Run Code Online (Sandbox Code Playgroud)
我想知道如果这是一个StringContent而不是像这样的ObjectContent会有什么不同?
objectContent = new StringContent(content);
objectContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
Run Code Online (Sandbox Code Playgroud)
两者都很好.因为它是JSON,我倾向于认为StringContent是有意义的.但是什么时候使用ObjectContent,因为几乎所有发送的内容都是"字符串".
我在asp.net core3.1中创建了一个http客户端。并通过启动注入它,它工作正常。
services.AddHttpClient<MyClient>();
Run Code Online (Sandbox Code Playgroud)
但是我无法控制它的日志输出。一直遵循此处的建议 https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-3.1#logging
我已经在我的配置中尝试了各种方法。目前看起来像这样
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning",
"System": "Error",
"System.Net.Http": "Warning",
"System.Net.Http.HttpClient": "Warning",
"System.Net.Http.HttpClient.MyClient.LogicalHandler": "Warning",
"System.Net.Http.HttpClient.MyClient.ClientHandler": "Warning",
"Microsoft.AspNetCore.Hosting": "Warning",
"Microsoft.Hosting.Lifetime": "Warning"
}
},
Run Code Online (Sandbox Code Playgroud)
但我不断收到信息日志,例如
Level":"Information","MessageTemplate":"Received HTTP response after {ElapsedMilliseconds}ms - {StatusCode}","Properties":{"ElapsedMilliseconds":895.4859,"StatusCode":"UnprocessableEntity","EventId":{"Id":101,"Name":"RequestEnd"}
"Level":"Information","MessageTemplate":"End processing HTTP request after {ElapsedMilliseconds}ms - {StatusCode}","Properties":{"ElapsedMilliseconds":932.1484,"StatusCode":"UnprocessableEntity","EventId":{"Id":101,"Name":"RequestPipelineEnd"}
Run Code Online (Sandbox Code Playgroud)
源上下文也在记录。这记录为 "SourceContext":"System.Net.Http.HttpClient.MyClient.ClientHandler" 在我看来排除了打字问题
我正在创建一个访问网站并登录的客户端+自动执行某些任务,但是他们最近更新了他们的cookie(无论出于何种原因......)在其标识cookie中包含逗号.
例如,Cookie将具有与此类似的值:
a,bcdefghijklmnop
Run Code Online (Sandbox Code Playgroud)
问题是,根据msdn,你不能在cookie的值中使用逗号或句点.我正在寻找的是解决这个限制的方法,某种方式使.net的Cookie与逗号的工作很好.我发现服务器确实向客户端发送了一个'SET-COOKIE'标题,我猜这是正在解析的内容,但这似乎也明显给commans和分号带来了特殊的意义(因此限制了.NET内部的类).
但是,IE,Firefox等浏览器如何正确处理cookie(正如他们显然那样,因为网站在我测试过的任何浏览器中都能正常工作.)是否有办法强迫这个在.NET中的行为?
任何帮助将不胜感激,谢谢.
一些额外的信息:
我的代码看起来像这样:
request = (HttpWebRequest)WebRequest.Create(URI);
request.CookieContainer = Program.client.cookieJar;
Run Code Online (Sandbox Code Playgroud)
其中cookieJar在Program.client中定义为:
CookieContainer cookieJar = new CookieContainer();
Run Code Online (Sandbox Code Playgroud)
当我遍历并打印出CookieContainer中的所有cookie时,我得到这样的结果:( cookies,格式为:"name" - >"value")
"normal_cookie" -> "i am the value"
"messedup_cookie" -> "a"
"bcdefghijklmnop" -> ""
// What I should get is this:
"normal_cookie" -> "i am the value"
"messedup_cookie" -> "a,bcdefghijklmnop"
Run Code Online (Sandbox Code Playgroud)
问题的核心似乎是逗号和半冒号是SET-COOKIE标题字符串中的保留字符...但是那么浏览器如何处理这个?我可以自己解析字符串,但我不知道如何绕过这样的情况:( HTTP标头,格式为:"name" - >"value")
"Set-Cookie" -> "messedup_cookie=a,bcdefghijklmnop; path=/; domain=.domain.com; expires=Sat, 15-Aug-2009 09:14:24 GMT,anothervariable=i am the value;"
Run Code Online (Sandbox Code Playgroud)
如您所见,expires部分查找逗号而不是分号,以区别于下一个变量.据我所知,它的格式如下:
cookie1_var1=value; cookie1_var2=value,cookie2_var1=value; cookir2_var2=value
Run Code Online (Sandbox Code Playgroud)
但如果这是真的,是否有一种优雅的方式来处理可能出现在其中一个值中的逗号?
我正在尝试将一个引用添加到Apache HttpClient(httpclient-4.0-beta2)中的http帖子.
我发现了一些示例代码.代码有效,但我想知道是否有一种更简单,更直接的方式来添加引用,而不是使用(不名称)addRequestInterceptor,它似乎将(yikes!)内部类作为参数.
有问题的代码从下面开始"//添加referer标题".我是新手,这段代码正在做一些我不理解的事情.这真的是在我的http帖子中添加引用者的最简单方法吗?
谢谢你的任何指示.
// initialize request parameters
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("firstName", "John"));
formparams.add(new BasicNameValuePair("lastName", "Doe"));
// set up httppost
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
HttpPost httppost = new HttpPost(submitUrl);
httppost.setEntity(entity);
// create httpclient
DefaultHttpClient httpclient = new DefaultHttpClient();
// add the referer header, is an inner class used here?
httpclient.addRequestInterceptor(new HttpRequestInterceptor()
{
public void process(final HttpRequest request,
final HttpContext context) throws HttpException, IOException
{
request.addHeader("Referer", referer);
}
});
// execute the request
HttpResponse response …Run Code Online (Sandbox Code Playgroud) 我有一个应用程序,它有一个线程池(ThreadPoolExecutor),它是每个执行HttpGet操作的传递任务,并将InputStream读入byte []以执行某些操作.
在阅读了HttpClient文档后,我得出的结论是,跨多个线程管理HttpClient连接的最佳方法是创建一个ThreadSafeClientConnManager并在整个应用程序中共享它.
实现这一点之后,我注意到即使在完成所有任务之后,仍然有大量内存仍由ThreadSafeClientConnManager使用.
查看堆转储,此内存采用byte []数组的形式.这些不是我创建的任何引用.它们由ThreadSafeClientConnManager及其池的各个部分保存.我不确定它们是否与InputStream相关或者它们是否是其他内容.
所有任务本身及其变量都被成功地垃圾收集.
如果我在ThreadSafeClientConnManager上调用getConnectionManager().shutdown(),则释放所有内存就好了.但是,我不想关闭连接,因为这些HttpGet任务可能随时发生.我希望在应用程序生命期间保持打开状态.
随着HttpGet任务的运行,持有的内存越来越多,最终可能导致内存不足错误.任务完成后,内存不会被释放.
在完成使用它的任务后,如何确保释放内存?
这是我正在使用的代码.它与HttpClient文档中的代码拼凑在一起,其他问题在SO和在线上.
HttpClient的创建:
// Create and initialize HTTP parameters
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 40 * 1000);
HttpConnectionParams.setSoTimeout(params, 40 * 1000);
ConnManagerParams.setMaxTotalConnections(params, 100);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
// Create and initialize scheme registry
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register( new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
// Create an HttpClient with the ThreadSafeClientConnManager.
// This connection manager must be used if more than one thread will
// be using the HttpClient. …Run Code Online (Sandbox Code Playgroud) 考虑以下程序,with all of HttpRequestMessage, and HttpResponseMessage, and HttpClient disposed properly.收集后最终总共会有大约50MB的内存.为请求数添加零,未回收的内存加倍.
class Program
{
static void Main(string[] args)
{
var client = new HttpClient {
BaseAddress = new Uri("http://localhost:5000/")};
var t = Task.Run(async () =>
{
var resps = new List<Task<HttpResponseMessage>>();
var postProcessing = new List<Task>();
for (int i = 0; i < 10000; i++)
{
Console.WriteLine("Firing..");
var req = new HttpRequestMessage(HttpMethod.Get,
"test/delay/5");
var tsk = client.SendAsync(req);
resps.Add(tsk);
postProcessing.Add(tsk.ContinueWith(async ts =>
{
req.Dispose();
var resp = ts.Result;
var content …Run Code Online (Sandbox Code Playgroud) httpclient ×10
c# ×5
java ×3
android ×2
memory-leaks ×2
.net ×1
.net-4.0 ×1
asp.net-core ×1
cookies ×1
filestream ×1
gzip ×1
http ×1
json ×1
logging ×1
memory ×1
mscorlib ×1
post ×1
request ×1
threadpool ×1