标签: httpclient

httpclient 返回乱码

我试图使用 HTTPClient 来获取页面,但它似乎返回乱码(我认为是二进制)。

这是我的代码:

public Boolean getPage(String url, String referer) {
    httpClient.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
    httpClient.getParams().setParameter("http.socket.timeout", new Integer(1000));
    httpClient.getParams().setParameter("http.protocol.content-charset", "UTF-8");

    HttpGet httpGet = new HttpGet(url);
    response = null;

    httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3");
    httpGet.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    httpGet.setHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
    httpGet.setHeader("Accept-Encoding", "gzip,deflate");
    httpGet.setHeader("Referer", referer);

    int tryNumber = 0;

    while(tryNumber<5){
        tryNumber++;
        try {
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            ret = httpClient.execute(httpGet,responseHandler).toString();
            Log.v("Info:", ret);
        }
        catch(Exception e) {
            error = e;
            break;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

谁能指出我哪里出错了?

我正在尝试获取此页面的内容: http: //hosh.me.uk/test.php

查看截图:http://img.ctrlv.in/4ecd69c40a590.jpg …

android httpclient

1
推荐指数
1
解决办法
1499
查看次数

HttpPost 在请求正文中发布复杂的 JSONObject

我想知道,使用 HttpClient 和 HttpPOST 有没有办法将复杂的 JSON 对象作为请求的正文发布?我确实看到了在正文中发布一个简单的键/值对的示例(如下图来自此链接:Http Post With Body):

HttpClient client= new DefaultHttpClient();
HttpPost request = new HttpPost("www.example.com");

List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("paramName", "paramValue"));

request.setEntity(new UrlEncodedFormEntity(pairs ));
HttpResponse resp = client.execute(request);
Run Code Online (Sandbox Code Playgroud)

但是,我需要发布如下内容:

{
"value": 
    {
        "id": "12345",
        "type": "weird",
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法让我做到这一点?

附加信息

执行以下操作:

HttpClient client= new DefaultHttpClient();
HttpPost request = new HttpPost("www.example.com");
String json = "{\"value\": {\"id\": \"12345\",\"type\": \"weird\"}}";
StringEntity entity = new StringEntity(json);
request.setEntity(entity);
request.setHeader("Content-type", "application/json");
HttpResponse resp = client.execute(request); 
Run Code Online (Sandbox Code Playgroud)

结果在服务器上是空的……因此我得到了 400。

提前致谢!

java httpclient apache-commons-httpclient apache-httpclient-4.x

1
推荐指数
1
解决办法
4113
查看次数

HttpClient 发送空的 POST 数据

嗯...我在 StackOverflow 中阅读了很多问题,但仍然没有得到答案,我有这个 Web API 控制器:

public class ERSController : ApiController
{
    [HttpGet]
    public HttpResponseMessage Get()
    {
        var resposne = new HttpResponseMessage(HttpStatusCode.OK);
        resposne.Content = new StringContent("test OK");
        return resposne;
    }

    [HttpPost]
    public HttpResponseMessage Post([FromUri]string ID,[FromBody] string Data)
    {
        var resposne = new HttpResponseMessage(HttpStatusCode.OK);
        //Some actions with database
        resposne.Content = new StringContent("Added");
        return resposne;
    }

}
Run Code Online (Sandbox Code Playgroud)

我给它写了一个小测试:

static void Main(string[] args)
{
    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri("http://localhost:54916/");
    client.DefaultRequestHeaders.Accept.Clear();


    var content = new StringContent("<data>Hello</data>", Encoding.UTF8, "application/json");

    var response …
Run Code Online (Sandbox Code Playgroud)

c# httpclient asp.net-web-api

1
推荐指数
1
解决办法
4888
查看次数

Angular HttpClient 错误处理困难

新 HttpClient https://angular.io/guide/http上的 Angular 文档 有一个“获取错误详细信息”部分,其中显示了如下示例。我已修改注释以记录我的观察结果,哪些基本错误类最终出现在何处。

http
.get<ItemsResponse>('/api/items')
.subscribe(
  data => {...},
  (err: HttpErrorResponse) => {
    if (err.error instanceof Error) {
      // we never seem to get here
      console.log('An error occurred:', err.error.message);
    } else {
      // no network connection, HTTP404, HTTP500, HTTP200 & invalid JSON
      console.log(`Backend returned code ${err.status}, body was: ${err.error}`);
    }
  }
);
Run Code Online (Sandbox Code Playgroud)

因此,至少 3 个完全不同类别的错误(网络、http、响应解析)出现在单个通道中,对于每种类型,必须在 HttpErrorResponse 的另一部分中搜索实际原因。

一个人只能识别一类,即通过标准错误代码的 HTTP 错误。但是另外两种呢?

当我拔下网络插头时,我得到了非常明显的 err.message = "Http failure response for (unknown url): 0 Unknown Error。" 描述性很强。

当新的内部 JSON 解析失败时,它表示存在语法错误 …

error-handling json httpclient angular

1
推荐指数
1
解决办法
4234
查看次数

为什么 Angular 6 不发送 HTTP Get/Post 请求?

我在 Angular 6 中有以下服务:

@Injectable()
export class LoginService {
    constructor(private http: HttpClient) { }

    login(): Observable<boolean> {
        var url = `${environment.baseAPIUrl}${environment.loginUrl}`;

        return this.http.get<boolean>(url);
    }
}
Run Code Online (Sandbox Code Playgroud)

我从我的组件调用它:

@Component({
    selector: 'bpms-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {

    constructor(private loginService: LoginService) { }

    ngOnInit() {
    }

    login() {
        var self = this;
        self.loginService.login();
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么它不发送我的请求?

开发者网络

httpclient typescript angular angular6

1
推荐指数
1
解决办法
1828
查看次数

使用 spfx webpart 中的 SPHttpClient 将文件上传到 SharePoint Online

我正在尝试在 spfx webpart 中使用 SPHttpClient 上传文件。

我正在尝试的代码是

const spOpts:ISPHttpClientOptions={body: { my: "bodyJson" } };

contextDetails.spHttpClient.post(url,SPHttpClient.configurations.v1, spOpts) 
       .then(response => { 
          return response; 
        }) 
      .then(json => { 
        return json; 
      }) as Promise<any>
Run Code Online (Sandbox Code Playgroud)

但我不确定如何将文件内容添加到这个 httpClient API。

我想我们必须在 body 参数中将文件内容添加到 spOpts 中。我不确定。

任何帮助表示赞赏。谢谢。

httpclient sharepoint-online spfx

1
推荐指数
1
解决办法
3442
查看次数

HTTP 客户端 NoCache 标志导致空引用异常 C#

我添加了这一行以在 HTTP 客户端中不应用缓存

HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.CacheControl.NoCache = true;
Run Code Online (Sandbox Code Playgroud)

当我运行之前运行良好的应用程序时,我在第二行中收到此异常:

NullReferenceException:未将对象引用设置为对象的实例

我试过这是应用运行良好的 NoChache 标志,但我不确定它是否符合预期。

HttpClient httpClient = new HttpClient()
{ 
    DefaultRequestHeaders=
    { 
        CacheControl = CacheControlHeaderValue.Parse("no-cache, no-store"),
        Pragma = { NameValueHeaderValue.Parse("no-cache")}
    }
};
Run Code Online (Sandbox Code Playgroud)

请帮助我应用正确的方法来设置 NoCache 标志。

c# httpclient pragma cache-control xamarin.forms

1
推荐指数
1
解决办法
1988
查看次数

在 .NET Core 2.2 中使用 SocketsHttpHandler 并忽略证书验证

使用HttpClientHandler,我们可以设置服务器验证回调并返回 true(通过写出或使用DangerousAcceptAnyServerCertificateValidator)。在升级到 .NET Core 2.2 后切换HttpClient到使用时,如何确保也绕过此验证SocketsHttpHandler?这是默认值吗?我目前找不到关于此主题的太多信息,我将部署到我希望避免进行重大更改的环境中。

c# certificate httpclient .net-core httpclienthandler

1
推荐指数
1
解决办法
891
查看次数

在大多数情况下,是什么让 Jsoup 比 HttpURLConnection 和 HttpClient 更快

我想比较标题中提到的三种实现的性能,我写了一个小 JAVA 程序来帮助我做到这一点。main 方法包含三个测试块,每个块看起来像这样:

        nb=0; time=0;
        for (int i = 0; i < 7; i++) {
            double v = methodX(url);
            if(v>0){
                nb++;
                time+=v;
            }
        }
        if(nb==0) nb=1;
        System.out.println("HttpClient : "+(time/ ((double) nb))+". Tries "+nb+"/7");
Run Code Online (Sandbox Code Playgroud)

变量nb用于避免失败的请求。现在方法methodX是以下之一:

    private static double testWithNativeHUC(String url){
        try {
            HttpURLConnection httpURLConnection= (HttpURLConnection) new URL(url).openConnection();
            httpURLConnection.addRequestProperty("User-Agent", UA);
            long before = System.currentTimeMillis();
            BufferedReader bufferedReader= new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
            while (bufferedReader.readLine()!=null);
            return System.currentTimeMillis()-before;
        } catch (IOException e) {
            e.printStackTrace();
            return -1;
        }
    }

    private static double testWithHC(String …
Run Code Online (Sandbox Code Playgroud)

java optimization httpclient httpurlconnection jsoup

1
推荐指数
1
解决办法
383
查看次数

无法在 Angular 10 中处理 HttpClient

当我尝试这样做时ng build,我收到一条错误消息

ERROR in node_modules/@angular/common/http/http.d.ts:81:22 - error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class.

This likely means that the library (@angular/common/http) which declares HttpClient has not been processed correctly by ngcc, or is not compatible with Angular Ivy. Check if a newer version of the library is available, and update if so. Also consider checking with the library's authors to see if the library is expected to be compatible …
Run Code Online (Sandbox Code Playgroud)

httpclient angular angular10

1
推荐指数
1
解决办法
1173
查看次数