我有一个web服务,它接受一个带有XML的POST方法.它工作正常,然后在一些随机的场合,它无法与服务器通信抛出IOException与消息The target server failed to respond.后续调用工作正常.
它主要发生在我打电话然后让我的应用程序闲置10-15分钟时.我之后的第一个调用会返回此错误.
我尝试了几件事......
我设置重试处理程序就像
HttpRequestRetryHandler retryHandler = new HttpRequestRetryHandler() {
public boolean retryRequest(IOException e, int retryCount, HttpContext httpCtx) {
if (retryCount >= 3){
Logger.warn(CALLER, "Maximum tries reached, exception would be thrown to outer block");
return false;
}
if (e instanceof org.apache.http.NoHttpResponseException){
Logger.warn(CALLER, "No response from server on "+retryCount+" call");
return true;
}
return false;
}
};
httpPost.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryHandler);
Run Code Online (Sandbox Code Playgroud)
但这次重试从未被召唤过.(是的,我正在使用right instanceof子句).虽然调试这个类永远不会被调用.
我甚至尝试过设置HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), false);但没有用.有人可以建议我现在能做什么吗?
重要 除了弄清楚为什么我得到例外之外,我所关注的一个重要问题是为什么重试操作员不在这里工作?
我正在尝试从ac#WPF桌面应用程序执行发布到我的WebAPI.
无论我做什么,我都会
{ "错误": "unsupported_grant_type"}
这就是我尝试过的(我已经尝试过所有可以找到的东西):
此外,dev web api目前正在进行测试:http://studiodev.biz/
基本http客户端对象:
var client = new HttpClient()
client.BaseAddress = new Uri("http://studiodev.biz/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
Run Code Online (Sandbox Code Playgroud)
使用以下发送方法:
var response = await client.PostAsJsonAsync("token", "{'grant_type'='password'&'username'='username'&'password'='password'");
var response = await client.PostAsJsonAsync("token", "grant_type=password&username=username&password=password");
Run Code Online (Sandbox Code Playgroud)
在那次失败后,我做了一些谷歌搜索并尝试:
LoginModel data = new LoginModel(username, password);
string json = JsonConvert.SerializeObject(data);
await client.PostAsync("token", new JsonContent(json));
Run Code Online (Sandbox Code Playgroud)
同样的结果,所以我试过:
req.Content = new StringContent(json, Encoding.UTF8, "application/x-www-form-urlencoded");
await client.SendAsync(req).ContinueWith(respTask =>
{
Application.Current.Dispatcher.Invoke(new Action(() => { label.Content = respTask.Result.ToString(); }));
});
Run Code Online (Sandbox Code Playgroud)
注意:我可以通过Chrome成功拨打电话.
更新Fiddler结果

请有人帮我成功拨打上述网页API …
情况就是这样:
他们是Servoy中的外部Web 服务,我想在ASP.NET MVC应用程序中使用此服务.
使用此代码,我尝试从服务中获取数据:
HttpResponseMessage resp = client.GetAsync("http://localhost:8080/servoy-service/iTechWebService/axws/shop/_authenticate/mp/112818142456/82cf1988197027955a679467c309274c4b").Result;
resp.EnsureSuccessStatusCode();
var foo = resp.Content.ReadAsAsync<string>().Result;
Run Code Online (Sandbox Code Playgroud)
但是当我运行应用程序时,我得到了下一个错误:
没有MediaTypeFormatter可用于从媒体类型为"text/plain"的内容中读取"String"类型的对象.
如果我打开Fiddler并运行相同的url,我会看到正确的数据,但内容类型是text/plain.但是我在Fiddler中也看到了我想要的JSON ......
是否有可能在客户端解决这个问题,还是Servoy Web服务?
更新:
使用HttpWebRequest而不是HttpResponseMessage并使用StreamReader读取响应...
import java.awt.List;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.omg.DynamicAny.NameValuePair;
public class Upload {
public static void main (String[] args) {
System.out.println(Imgur("C:\\Users\\username\\Desktop\\image.jpg", "clientID"));
}
public static String Imgur (String imageDir, String clientID) {
//create needed strings
String address = "https://api.imgur.com/3/image";
//Create HTTPClient and post
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(address);
//create base64 image
BufferedImage …Run Code Online (Sandbox Code Playgroud) 我有以下测试代码.循环316934或361992次后,我总是得到"任务被取消"错误.
如果我没有错,那么任务被取消的原因有两个:a)HttpClient超时或b)队列中的任务太多而某些任务超时.
我找不到关于排队任务的限制的文档.我尝试创建超过500K的任务,没有超时.我猜"b"的原因可能不对.
Q1.我错过了还有其他原因吗?
Q2.如果是因为HttpClient超时,我怎么能得到确切的异常消息而不是"TaskCancellation"异常.
Q3.什么是解决它的最佳方法?我应该介绍一下节流器吗?
谢谢!
var _httpClient = new HttpClient();
_httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "text/html,application/xhtml+xml,application/xml");
_httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
_httpClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:19.0) Gecko/20100101 Firefox/19.0");
_httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Charset", "ISO-8859-1");
int[] intArray = Enumerable.Range(0, 600000).ToArray();
var results = intArray
.Select(async t => {
using (HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, "http://www.google.com")) {
log.Info(t);
try {
var response = await _httpClient.SendAsync(requestMessage);
var responseContent = await response.Content.ReadAsStringAsync();
return responseContent;
}
catch (Exception ex) {
log.ErrorException(string.Format("SoeHtike {0}", Task.CurrentId), ex);
}
return null;
}
});
Task.WaitAll(results.ToArray());
Console.ReadLine(); …Run Code Online (Sandbox Code Playgroud) 所以,我得出结论,Apache HttpComponents 4是我遇到过的最烦人的API之一.看起来他们应该很简单的事情就是花费数百行代码(我仍然不确定资源是否正确清理).
另外它要我做的事情如下:
List<NameValuePair> qparams = new ArrayList<NameValuePair>();
qparams.add(new BasicNameValuePair("q", "httpclient"));
qparams.add(new BasicNameValuePair("btnG", "Google Search"));
qparams.add(new BasicNameValuePair("aq", "f"));
qparams.add(new BasicNameValuePair("oq", null));
URI uri = URIUtils.createURI("http", "www.google.com", -1, "/search",
URLEncodedUtils.format(qparams, "UTF-8"), null);
Run Code Online (Sandbox Code Playgroud)
哪个,只是......不.我知道它是Java,我们并不是整个简洁的事情,但这有点多了.更不用说罐子高达700KB.
无论如何,足够的咆哮,我想看看人们与其他HTTP客户端库有什么样的体验?
我所知道的是:Jetty,hotpotato和AsyncHttpClient.
这是为了服务器端使用,我最感兴趣的是许多并发获取和大文件传输的性能.
有什么建议?
PS我知道古老的HttpClient 3.1仍然存在,但我想使用支持的东西.
@oleg:这是文档的建议:
HttpClient httpclient = new DefaultHttpClient();
try {
HttpGet httpget = new HttpGet("http://www.apache.org/");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
try { …Run Code Online (Sandbox Code Playgroud) 这是代码:
HttpClient client = null;
HttpClientHandler httpClientHandler = new HttpClientHandler()
{
Proxy = new WebProxy(string.Format("{0}:{1}", proxyServerSettings.Address,
proxyServerSettings.Port),false),
PreAuthenticate = true,
UseDefaultCredentials = false,
};
this.httpClientHandler.Credentials = new NetworkCredential(proxyServerSettings.UserName,
proxyServerSettings.Password);
this.client = new HttpClient(this.httpClientHandler);
Run Code Online (Sandbox Code Playgroud)
当我最终这样做时:
HttpResponseMessage httpResponseMessage = this.client.PostAsync(urlToPost, new StringContent(data, Encoding.UTF8, this.mediaType)).Result;
Run Code Online (Sandbox Code Playgroud)
它总是抛出
远程服务器返回错误:(407)需要代理身份验证.
对于我这个世界,我不明白.
在IE10中配置或者我使用HttpWebRequest该类时,相同的代理设置工作正常
我试图通过拦截器实现HttpCache.以下是caching-interceptor.service.ts
import { HttpRequest, HttpResponse, HttpInterceptor, HttpHandler, HttpEvent } from '@angular/common/http'
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import 'rxjs/add/observable/of';
export abstract class HttpCache {
abstract get(req: HttpRequest<any>): HttpResponse<any>|null;
abstract put(req: HttpRequest<any>, resp: HttpResponse<any>): void;
}
@Injectable()
export class CachingInterceptor implements HttpInterceptor {
constructor(private cache: HttpCache) {}
intercept(req: HttpRequest<any>, next: HttpHandler) : Observable<HttpEvent<any>> {
if(req.method !== 'GET'){
return next.handle(req);
}
const cachedResponse = this.cache.get(req);
if(cachedResponse){
return Observable.of(cachedResponse);
}
return next.handle(req).do(event => {
if(event …Run Code Online (Sandbox Code Playgroud) 我已经编写了下面的代码来发送标题,发布参数.问题是我使用SendAsync,因为我的请求可以是GET或POST.如何将POST Body添加到此代码中,以便如果有任何帖子正文数据,则会在我发出的请求中添加它,如果它的简单GET或POST没有正文,则会以此方式发送请求.请更新以下代码:
HttpClient client = new HttpClient();
// Add a new Request Message
HttpRequestMessage requestMessage = new HttpRequestMessage(RequestHTTPMethod, ToString());
// Add our custom headers
if (RequestHeader != null)
{
foreach (var item in RequestHeader)
{
requestMessage.Headers.Add(item.Key, item.Value);
}
}
// Add request body
// Send the request to the server
HttpResponseMessage response = await client.SendAsync(requestMessage);
// Get the response
responseString = await response.Content.ReadAsStringAsync();
Run Code Online (Sandbox Code Playgroud) 我正在努力实现这个休息api:
public async Task<bool> AddTimetracking(Issue issue, int spentTime)
{
// POST /rest/issue/{issue}/timetracking/workitem
var workItem = new WorkItem(spentTime, DateTime.Now);
var httpContent = new StringContent(workItem.XDocument.ToString());
var requestUri = string.Format("{0}{1}issue/{2}/timetracking/workitem", url, YoutrackRestUrl, issue.Id);
var respone = await httpClient.PostAsync(requestUri, httpContent);
if (!respone.IsSuccessStatusCode)
{
throw new InvalidUriException(string.Format("Invalid uri: {0}", requestUri));
}
return respone.IsSuccessStatusCode;
}
Run Code Online (Sandbox Code Playgroud)
workItem.XDocument 包含以下元素:
<workItem>
<date>1408566000</date>
<duration>40</duration>
<desciption>test</desciption>
</workItem>
Run Code Online (Sandbox Code Playgroud)
我从API收到错误: Unsupported Media Type
我真的不知道如何解决这个问题,非常感谢帮助.如何使用HTTP POST URI 编组 XML文件HttpClient?