标签: httpclient

org.apache.http.ProtocolException:未指定目标主机

我写了一个简单的httprequest /响应代码,我得到以下错误.我在类路径中引用了httpclient,httpcore,common-codecs和common-logging.我是java的新手,不知道这里发生了什么.请帮我.

码:

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.HttpResponse;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.Header;
import org.apache.http.HttpHeaders;

public class UnshorteningUrl {

    public static void main(String[] args) throws Exception
    {           
        HttpGet request=null;
        HttpClient client = HttpClientBuilder.create().build();         

        try {
            request = new HttpGet("trib.me/1lBFzSi");
            HttpResponse httpResponse=client.execute(request);

            Header[] headers = httpResponse.getHeaders(HttpHeaders.LOCATION);
           // Preconditions.checkState(headers.length == 1);
            String newUrl = headers[0].getValue();          
            System.out.println("new url" + newUrl);         
        } catch (IllegalArgumentException e) {
            // TODO: handle exception
        }finally {
            if (request != null) {
                request.releaseConnection();
            }           
        }
    }}
Run Code Online (Sandbox Code Playgroud)

错误:

Exception in …
Run Code Online (Sandbox Code Playgroud)

java httpresponse httpclient apache-httpclient-4.x

21
推荐指数
1
解决办法
4万
查看次数

HttpClient 4.1的SSL"Peer Not Authenticated"错误

我正在构建一个简单的应用程序监视器来轮询我们的一个API URL并向我们发送电子邮件,如果它无法从响应中获取HTTP 200状态代码(这表明我们的API因某种原因而关闭).

我正在使用HttpClient 4.1(这很重要,因为它的API与3.x 差别很大).

我们的API使用SSL是安全的,但输入:

http://example.com/our-api

进入Web浏览器重定向到

https://example.com/our-api

没有造成任何错误.

当HttpClient尝试命中此URL(http://example.com/our-api)时,它会失败并显示javax.net.ssl.SSLPeerUnverifiedException一条消息,指出:

peer未经过身份验证

我看到这对其他人来说发生了很多事情,正如这篇文章所证明的那样(这也提供了一些规避这个问题的方法 - 我将在今晚尝试和实施的解决方案).

这个其他帖子(和其他类似的帖子)没有做的是解释为什么这首先发生!所以,而不是问"我该如何解决这个问题?" 我想我会问" 为什么会发生这种情况? "在我提前解决其中一个建议的解决方案之前,我想知道我试图解决的问题是什么;-)

java ssl httpclient ssl-certificate

20
推荐指数
2
解决办法
10万
查看次数

HttpClient不在CookieContainer中存储cookie

我正在使用VS2010+ .NET 4.0+ System.Net.Http(来自Nuget).

由于我无法理解的原因,我收到的会话cookie HttpResponseMessage不会自动保存在HttpClient CookieContainer.这是我的代码的样子:

CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;
HttpClient client = new HttpClient(handler);

Uri site = new Uri("https://www.mywebsite.com");
var response1 = client.SendAsync(new HttpRequestMessage(HttpMethod.Get,site)).Result;
Run Code Online (Sandbox Code Playgroud)

我可以在响应头中看到我有以下内容:

Set-Cookie: JSESSIONID=FC8110E434C2C6DAB78B4E335024A639; Path=/member; Secure
Run Code Online (Sandbox Code Playgroud)

但是我的cookie容器仍然是空的...为什么?

c# cookies httpclient

20
推荐指数
2
解决办法
3万
查看次数

HttpClientHandler/HttpClient内存泄漏

我有10到150个长生命类对象,可以调用使用HttpClient执行简单HTTPS API调用的方法.PUT调用示例:

using (HttpClientHandler handler = new HttpClientHandler())
{
    handler.UseCookies = true;
    handler.CookieContainer = _Cookies;

    using (HttpClient client = new HttpClient(handler, true))
    {
        client.Timeout = new TimeSpan(0, 0, (int)(SettingsData.Values.ProxyTimeout * 1.5));
        client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", Statics.UserAgent);

        try
        {
            using (StringContent sData = new StringContent(data, Encoding.UTF8, contentType))
            using (HttpResponseMessage response = await client.PutAsync(url, sData))
            {
                using (var content = response.Content)
                {
                    ret = await content.ReadAsStringAsync();
                }

            }
        }
        catch (ThreadAbortException)
        {
            throw;
        }
        catch (Exception ex)
        {
            LastErrorText = ex.Message;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

运行这些方法2-3个小时后,包括通过 …

c# memory garbage-collection memory-leaks httpclient

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

如何在HttpClient"get"方法中传递URLSearchParams - Angular 5

我使用Angular 4.2Http服务,我使用了这样的get方法,其中params是一个URLSearchParams对象:

this.http.get(url, {headers: this.setHeaders(), search: params})
Run Code Online (Sandbox Code Playgroud)

我想迁移到Angular 5.http现在是一个像角度团队推荐的HttpClient对象.我的'搜索'键出错了.

你知道如何在我的案例中将Http迁移到HttpClient服务吗?

谢谢.

http httpclient angular angular5

20
推荐指数
2
解决办法
4万
查看次数

android httpclient挂起第二次请求到服务器(连接超时)

我正在努力解决以下问题:我的应用程序使用HttpClient向http服务器发出一系列请求.我使用HttpPut将数据发送到服务器.第一个请求进行得很快,第二个请求挂起40秒,然后我抓住Connection超时异常.我正在尝试重用我的HttpClient并通过同一个实例发送第二个请求.如果我与新的ConnectionManager一起创建新的HttpClient,那么一切正常.

为什么会这样?以及如何修复它并且每次都不创建新的HttpClient?

提前致谢.

这是我的代码:(如果我在doPut中评论readClient = newHttpClient(readClient),那么问题就出现了.

public class WebTest
{
private HttpClient readClient;
private SchemeRegistry httpreg;
private HttpParams params;

private URI url; //http://my_site.net/data/

protected HttpClient newHttpClient(HttpClient oldClient)
{
    if(oldClient != null)
        oldClient.getConnectionManager().shutdown();

    ClientConnectionManager cm = new SingleClientConnManager(params, httpreg);
    return new DefaultHttpClient(cm, params);
}

protected String doPut(String data)
{
    //****************************
    //Every time we need to send data, we do new connection
    //with new ConnectionManager and close old one
    readClient = newHttpClient(readClient);

    //*****************************


    String responseS = null;
    HttpPut put = new HttpPut(url); …
Run Code Online (Sandbox Code Playgroud)

android httpclient

19
推荐指数
3
解决办法
2万
查看次数

android中的https(无对等证书)问题

问题

我想将https请求发送到我自己的服务器站点https://10.2.20.20/fido/EzPay/login.php并从中获取响应,并将其保存为例如字符串.我在互联网上找到了一些示例代码,并尝试测试它们以解决我的问题,但它们没有帮助.下面我介绍一些我测试过的代码部分.


代码示例:

我试试这段代码,但我总是得到同样的例外"没有同行证书"为什么?

try
{
    HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

    DefaultHttpClient client = new DefaultHttpClient();

    SchemeRegistry registry = new SchemeRegistry();
    SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
    socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
    registry.register(new Scheme("https", socketFactory, 443));
    SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
    DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());

    // Set verifier      
    HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

    // Example send http request
    final String url = "https://10.2.20.20/fido/EzPay/login.php";
    HttpPost httpPost = new HttpPost(url);
    HttpResponse response = httpClient.execute(httpPost);

    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    String line = "";
    while ((line = …
Run Code Online (Sandbox Code Playgroud)

java https android httpclient

19
推荐指数
2
解决办法
5万
查看次数

SSLPeerUnverifiedException:peer未经过身份验证

再一次,SSLPeerUnverified的沉闷问题,但我没有使用自签名证书.我尝试使用https连接到主机.该主机具有正确的证书,Firefox和HttpsUrlConnection都没有任何问题.无论如何尝试使用HttpClient进行连接,我都会遇到可怕的异常.

有线索吗?或者提示哪里看得更近?

谢谢!

编辑:调试输出

main,处理异常:

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: 
sun.security.provider.certpath.SunCertPathBuilderException: 
unable to find valid certification path to requested target
Run Code Online (Sandbox Code Playgroud)

main,getSession()中的IOException:

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: 
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: 
unable to find valid certification path to requested target
Run Code Online (Sandbox Code Playgroud)

java httpclient

19
推荐指数
1
解决办法
4万
查看次数

HttpClient在使用语句中

嗨,我读到这篇文章你正在使用HttpClient错误,它正在破坏你的软件,文章建议这些2

  1. 使您的HttpClient静态
  2. 除非您明确要查找特定行为(例如导致服务失败),否则不要将HttpClient丢弃或包装在使用中

现在像我这样的c#上的新手就会跟着它,就像这篇文章上发布的代码是原始代码,他说会使应用程序失败

using System;
using System.Net.Http;
namespace ConsoleApplication
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Starting connections");
            for(int i = 0; i<10; i++)
            {
                using(var client = new HttpClient())
                {
                    var result = client.GetAsync("http://aspnetmonsters.com").Result;
                    Console.WriteLine(result.StatusCode);
                }
            }
            Console.WriteLine("Connections done");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

并修复它,他给了这个代码:

using System;
using System.Net.Http;
namespace ConsoleApplication
{
    public class Program
    {
        private static HttpClient Client = new HttpClient();
        public static void Main(string[] args)
        {
            Console.WriteLine("Starting connections");
            for(int i = …
Run Code Online (Sandbox Code Playgroud)

c# httpclient

19
推荐指数
2
解决办法
3万
查看次数

使用WebClient或HttpClient下载文件?

我试图从URL下载文件,我必须在WebClient和HttpClient之间进行选择.我在互联网上引用了这篇文章和其他几篇文章.无处不在,由于其非常好的异步支持和其他.Net 4.5权限,建议使用HttpClient.但我仍然不完全相信并需要更多的投入.

我使用下面的代码从互联网上下载文件:

Web客户端:

WebClient client = new WebClient();
client.DownloadFile(downloadUrl, filePath);
Run Code Online (Sandbox Code Playgroud)

HttpClient的:

using (HttpClient client = new HttpClient())
{        
    using (HttpResponseMessage response = await client.GetAsync(url))
    using (Stream streamToReadFrom = await response.Content.ReadAsStreamAsync())
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

从我的角度来看,我只能看到使用WebClient的一个缺点,那就是非异步调用,阻塞调用线程.但是,如果我不担心阻塞线程或使用client.DownloadFileAsync()异步支持,该怎么办?

另一方面,如果我使用HttpClient,是不是我将文件的每个字节加载到内存中然后将其写入本地文件?如果文件太大,内存开销不会很贵吗?如果我们使用WebClient可以避免这种情况,因为它将直接写入本地文件而不会消耗系统内存.

那么,如果性能是我的首要任务,我应该使用哪种方法进行下载?如果我的上述假设是错误的,我想澄清一下,我也愿意接受替代方法.

.net c# rest webclient httpclient

19
推荐指数
5
解决办法
4万
查看次数