标签: apache-httpcomponents

Apache HttpClient响应内容长度返回-1

为什么以下代码返回-1?似乎请求失败.

public static void main(String[] args)
{
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet("http://www.google.de");

    HttpResponse response;
    try
    {
        response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        EntityUtils.consume(entity);

        // Prints -1
        System.out.println(entity.getContentLength());
    }
    catch (ClientProtocolException e)
    {
        e.printStackTrace();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    finally
    {
        httpGet.releaseConnection();
    }
}
Run Code Online (Sandbox Code Playgroud)

是否可以将响应作为String?

java http apache-httpcomponents

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

使用CloseableHttpClient的不受支持的记录版本SSLv2Hello

我正在尝试进行https调用并收到以下错误:不支持的记录版本SSLv2Hello

任何人都可以对我做错的事情有所了解吗?谢谢你的帮助.

这是StackTrace:

    debug:
    Unsupported record version SSLv2Hello
    javax.net.ssl.SSLException: Unsupported record version SSLv2Hello
    at sun.security.ssl.InputRecord.readV3Record(Unknown Source)
    at sun.security.ssl.InputRecord.read(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
    at org.apache.http.conn.ssl.SSLConnectionSocketFactory.createLayeredSocket(SSLConnectionSocketFactory.java:275)
    at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:254)
    at org.apache.http.impl.conn.HttpClientConnectionOperator.connect(HttpClientConnectionOperator.java:123)
    at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:318)
    at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:363)
    at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:219)
    at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:195)
    at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:86)
    at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:108)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
    at httpcomponents.httpsTest.main(httpsTest.java:135)
    

这是工作示例:

    import com.sun.net.ssl.internal.ssl.Provider;
    import java.io.IOException;
    import java.security.KeyManagementException;
    import java.security.NoSuchAlgorithmException;
    import java.security.SecureRandom;
    import java.security.Security;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    import java.text.MessageFormat;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Timer; …

java ssl apache-httpcomponents

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

java 11 上的 SSL 通信期间发生 SocketException 时,如何使用 DefaultHttpRequestRetryHandler(HTTPClient) 重试?

我应该如何实现它才能在 java11 上使用httpclient重试 SSL 通信?

如下所示覆盖 DefaultHttpRequestRetryHandler 是否更好?
有没有更好的办法?

  public class HttpRequestRetryHandler extends DefaultHttpRequestRetryHandler {

    @Override
    public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
      IOException cause = exception;
      if (exception instanceof SSLException) {
        if (exception.getCause() != null && exception.getCause() instanceof IOException) {
          cause = (IOException) exception.getCause();
        }
      }
      return super.retryRequest(cause, executionCount, context);
    }
  }
Run Code Online (Sandbox Code Playgroud)

在 Java 11 中,不会重试 SocketException,因为 SocketException 是用 SSLException 包装的。

我阅读了以下内容。

java httpclient apache-httpcomponents java-11

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

内容长度无效发送到服务器?

我正试图通过他们的新API通过此处记录的方法将照片上传到热门服务Dailybooth .

问题是服务器响应:

<html><head><title>411 Length Required</title>...
Run Code Online (Sandbox Code Playgroud)

我用来发送这些数据的代码在这里:

// 2: Build request
HttpClient httpclient = new DefaultHttpClient();
SharedPreferences settings = DailyboothShared.getPrefs(DailyboothTakePhoto.this);
String oauth_token = settings.getString("oauth_token", "");
HttpPost httppost = new HttpPost(
        "https://api.dailybooth.com/v1/pictures.json?oauth_token=" + oauth_token);
Log.d("upload", "Facebook: " + facebook);
Log.d("upload", "Twitter: " + twitter);
try {
    InputStream f = getContentResolver().openInputStream(snap_url);
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    entity.addPart("picture", new InputStreamBody(f, snap_url.getLastPathSegment()));
    entity.addPart("blurb", new StringBody(blurb));
    entity.addPart("publish_to[facebook]", new StringBody(facebook));
    entity.addPart("publish_to[twiter]", new StringBody(twitter));
    httppost.setEntity(entity);
    HttpResponse response = httpclient.execute(httppost);
    Log.d("upload", response.toString());
    int statusCode = response.getStatusLine().getStatusCode(); …
Run Code Online (Sandbox Code Playgroud)

java android apache-httpcomponents

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

Apache-HttpComponents:套接字关闭错误

我正在编写一个Java程序,该程序使用Apache-HttpComponents加载页面并将其HTML打印到控制台。但是,该程序仅在抛出此错误之前打印HTML Exception in thread "main" java.net.SocketException: socket closed.的一部分:每次运行程序时,在异常之前显示的HTML部分完全相同,并且在使用Google,Yahoo和Craigslist的此简化示例中会发生错误:

String USERAGENT = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22";
DefaultHttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("http://www.craigslist.org");
get.setHeader(HTTP.USER_AGENT,USERAGENT);
HttpResponse page = client.execute(get);
get.releaseConnection();
InputStream stream = page.getEntity().getContent();
try{
    BufferedReader br = new BufferedReader(new InputStreamReader(stream));
    String line = "";
    while ((line = br.readLine()) != null){
        System.out.println(line);
    }
}
finally{
    EntityUtils.consume(page.getEntity());
}
Run Code Online (Sandbox Code Playgroud)

java apache-httpcomponents

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

Apache HttpClientBuilder - IllegalArgumentException

IllegalArgumentException试图用HttpClientBuilder构建Apache HttpClient实例时得到:

private CloseableHttpClient delegate;

public DigestClient(String user, String pass) {
    Credentials credentials = new UsernamePasswordCredentials(user, pass);

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, credentials);

    delegate = HttpClientBuilder.create()
            .setDefaultCredentialsProvider(credentialsProvider)
            .build();
}
Run Code Online (Sandbox Code Playgroud)

我得到的是:

 java.lang.IllegalArgumentException: Item may not be null
        at org.apache.http.util.Args.notNull(Args.java:48)
        at org.apache.http.config.RegistryBuilder.register(RegistryBuilder.java:58)
        at org.apache.http.impl.client.HttpClientBuilder.build(HttpClientBuilder.java:727)
        at com.example.app.data.net.DigestClient.<init>(DigestClient.java:51)
Run Code Online (Sandbox Code Playgroud)

任何想法为什么会这样?

这是我与HttpClient版本的关系:

compile 'org.apache.httpcomponents:httpclient-android:4.3.5'
Run Code Online (Sandbox Code Playgroud)

java android httpclient apache-httpcomponents apache-httpclient-4.x

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

MultipartEntity:InputStream的Content-Length

我正在尝试从multipart/form-data中的输入流发送数据,作为文件参数使用:

MultipartEntityBuilder.create()
            .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
            .addBinaryBody("file", inputStream)
            .build();
Run Code Online (Sandbox Code Playgroud)

问题是服务器似乎需要Content-Length标头.我知道inputStream的大小正确 - 我可以手动设置吗?

java apache-httpcomponents

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

log4j 2 不显示依赖日志

我正在使用 apache HttpClient 来执行 POST 请求:

CloseableHttpResponse response = HttpClients.createDefault().execute(request);

我想在日志中看到请求(和其他 apache 客户端库日志语句),但我只能看到我的应用程序日志,没有任何依赖项的其他日志。

这是我的log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
    <Appenders>
        <Lambda name="Lambda">
            <PatternLayout>
                <pattern>%d %X{AWSRequestId} %t %-5p [%X{userId}] %c{1}:%L - %m%n</pattern>
            </PatternLayout>
        </Lambda>
    </Appenders>
    <Loggers>
        <Logger name="org.apache.http" level="debug">
            <AppenderRef ref="Lambda"/>
        </Logger>
        <Root level="debug">
            <AppenderRef ref="Lambda"/>
        </Root>
    </Loggers> 
</Configuration>
Run Code Online (Sandbox Code Playgroud)

使用这个答案,我添加了以下内容,但它仍然没有显示 apache 日志。

    <Logger name="org.apache.http.client" level="debug">
        <AppenderRef ref="Lambda"/>
    </Logger>
    <Logger name="org.apache.http.impl.client" level="debug">
        <AppenderRef ref="Lambda"/>
    </Logger>
    <Logger name="org.apache.http.impl.conn" level="debug">
        <AppenderRef ref="Lambda"/>
    </Logger>
Run Code Online (Sandbox Code Playgroud)

我可以确认log4j2.xmllog4j 正在使用它,因为日志遵循<pattern>我写的。

我错过了什么?请帮忙。

java log4j apache-httpcomponents apache-httpclient-4.x log4j2

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

为什么 apache httpclient 连接池中的过时连接检查不是 100% 可靠

2.5. Connection eviction policy在 httpclient 的文档 连接管理文档部分中提到

HttpClient 尝试通过测试连接是否“过时”来缓解该问题,该连接在使用连接执行 HTTP 请求之前已在服务器端关闭,因此不再有效。过时连接检查并非 100% 可靠。

我只是想知道为什么无法可靠地检查过时的连接?什么逻辑/TCP 构造不允许它可靠地发生?

java tcp apache-httpcomponents apache-httpclient-4.x

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

Apache HttpClient 抛出 java.net.SocketException:如果我将其用作单例,则连接重置

我创建了一个 Apache HTTP 客户端

             CloseableHttpClient client = HttpClients.custom()
                .setMaxConnPerRoute(25)
                .setMaxConnTotal(50)
                .setDefaultRequestConfig(RequestConfig.custom()
                        .setConnectionRequestTimeout(20_000)
                        .build())
                .build();
Run Code Online (Sandbox Code Playgroud)

我将它用作单例。我有这种发送请求的方法:

public RestResponse sendPost(String serverUrl, String body) throws RestException {
        try {
            HttpPost httpPost = new HttpPost(serverUrl);
            httpPost.setEntity(new StringEntity(body));

            try (CloseableHttpResponse response = client.execute(httpPost)) {
                RestResponse restResponse = new RestResponse();
                restResponse.setCode(response.getStatusLine().getStatusCode());
                restResponse.setBody(EntityUtils.toString(response.getEntity()));
                return restResponse;
            }
        } catch (Exception e) {
            throw new RestException(e);
        }
    }
Run Code Online (Sandbox Code Playgroud)

效果很好。但是闲置一段时间(5-6 分钟)后,如果我发送请求,我会得到"java.net.SocketException: Connection reset"

我有 2 个问题

  1. 我怎样才能找到这个时间开始的地方?这些参数对我不起作用

                 .setSocketTimeout(25_000)
                 .setConnectTimeout(26_000)
    
    Run Code Online (Sandbox Code Playgroud)
  2. 解决这个问题的最佳方法是什么?(我的意思是在每个请求之后或之前重试请求或更改超时或重新连接)

java socket-timeout-exception apache-httpcomponents apache-httpclient-4.x

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