标签: httpconnection

Apache HTTPClient不会超过2个连接

我一直在尝试使用Apache HTTPClient(v4.1)为我的应用程序实现连接池.问题是客户端在运行时总是只创建两个连接,尽管有足够的线程并行运行.我一直试图修改代码一段时间,但没有任何帮助.
我正在使用ThreadSafeClientConnManager连接池并设置我想要的值MaxTotalDefaulMaxPerRoute值.
首先我想到的是你想要检查的东西吗?

这是我用来创建客户端的代码段.

DefaultHttpClient createClient() {
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, new Integer(60000));
    params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, new Integer(60000));
    params.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true);

    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("https", sf, 6443));
    registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));

    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, registry);
    cm.setMaxTotal(2 * maxConnections);
    cm.setDefaultMaxPerRoute(maxConnections);

    HttpHost localhost = new HttpHost("localhost");
    cm.setMaxForRoute(new HttpRoute(localhost), maxConnections);

    HttpHost sdpTargetHost = new HttpHost("webserviceIP", webservicePort, "https");
    cm.setMaxForRoute(new HttpRoute(sdpTargetHost, null, true), maxConnections);

    return new DefaultHttpClient(cm, params);
}
Run Code Online (Sandbox Code Playgroud)

此函数返回的客户端由 …

java httpconnection apache-httpclient-4.x

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

给出 java.lang.IllegalStateException 的 setRequestProperty 方法:建立连接后无法设置方法

HttpURLConnection con = null;
        Response response = new Response();
        String TAG = "HttpConHandler";

        try{
            /*
             * IMPORTANT: 
             * User SHOULD provide URL Encoded Parms
             */
            Log.p(TAG, "URL="+ urlStr);
            String q=httpHeaders.get("Authorization");

            URL url = new URL(urlStr);
            con = (HttpURLConnection) url.openConnection(); 

            con.setRequestProperty("Authorization", q);
            con.setRequestProperty("GData-Version", "3.0");
Run Code Online (Sandbox Code Playgroud)

嗨,我在调用方法时遇到java.lang.IllegalStateException: Cannot set method after connection is made错误setRequestProperty,但是当我在连接之前调用此方法时,我得到了NullPointerException因为con为空。我能做些什么来解决这个问题?

java android httpconnection

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

如何在Android中将图像上传到服务器?

我正在尝试通过相机将图像捕获上传到服务器.服务器发送响应代码= 200但Image不上传到服务器.

代码是:

private boolean uploadData() {

    int count = this.forumThreadsB.size();
    for (int i = 0; i < count; i++)
    {
            if (isPhoto)
                message = "Uploading Shared Items " + (i + 1) + " of " + count;
            else
                message = "Uploading Shared Items " + (i + 1) + " of " + count;

            progressCount = (i * 1000)/count; 
            Hashtable<?, ?> threadD = (Hashtable<?, ?>)this.forumThreadsB.elementAt(i);

            String onlinePath = "http://xyx.com/;
            threadid = (String) threadD.get("devicethreadid");
            Hashtable<String, String> pairs = new …
Run Code Online (Sandbox Code Playgroud)

android file-upload image httprequest httpconnection

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

How to get the socket used by HttpURLConnection in java

有一个套接字,HttpURLConnection在内部使用该套接字发送数据。我知道它现在可以从外部看到,但是我想知道是否有任何解决方法,以便我可以访问此套接字(而无需更改HttpURLConnection的实现)?我需要这个技巧来做一些检测。

非常感谢。

java sockets httpconnection

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

如何检查防火墙是否阻止了URL

我正在尝试检查URL是否可访问.我正在使用HttpURLConnection.现在我正在实施它.

public static boolean isUrlAccessible(final String urlToValidate)
            throws WAGException {
        URL url = null;
        HttpURLConnection huc = null;
        int responseCode = -1;
        try {
            url = new URL(urlToValidate);
            huc = (HttpURLConnection) url.openConnection();
            huc.setRequestMethod("HEAD");
            huc.connect();
            responseCode = huc.getResponseCode();
        } catch (final UnknownHostException e) {
            e.printStackTrace();
            System.out.println(e.getMessage()+" "+e.getLocalizedMessage());
            return false;
        } catch (final MalformedURLException e){
            e.printStackTrace();
            System.out.println(e.getMessage()+" "+e.getLocalizedMessage());
            return false;
        } catch (ProtocolException e) {
            e.printStackTrace();
            System.out.println(e.getMessage()+" "+e.getLocalizedMessage());
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(e.getMessage()+" "+e.getLocalizedMessage());
            return false;
        } finally …
Run Code Online (Sandbox Code Playgroud)

java url firewall httpconnection

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

如何处理网络问题

我的一个应用程序使用大量HTTP请求与其后端进行通信.我使用2种不同的实现来执行这些请求:

  • Volley大多数情况下的库
  • 的组合AsyncTask,并DefaultHttpClient为少数病例

大多数时候,一切都运作良好.但有时我会提出一系列网络异常,并将其展示给Crashlytics:

  • java.net.UnknownHostException: Unable to resolve host "mydomain.com": No address associated with hostname Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)

  • com.android.volley.ServerError at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:175) at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:110)

通过一些研究,我发现这应该发生在设备有一个非常糟糕的3g/4g或在VPN /子网后面,所以它无法到达我的网站.

如何确保设备真正连接到互联网?我实际上只有在此函数返回true时才执行这些请求:

public static boolean isOnline(Context ctx) {
        ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            return true;
        }
        return false;
}
Run Code Online (Sandbox Code Playgroud)

或者我应该放手,并假设每月达到几百个这样的警告是正常的?

java android httpconnection android-networking android-volley

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

在iOs和浏览器上API调用比在android上快得多

HttpsConnection在Android上遇到了麻烦.

首先,不,它不是重复.我在SO上尝试了几乎所有的解决方案,比如更改keep-alive选项或者timeout(其中一些确实优化了我的代码的一部分)但是它在Android上比在iOS上慢5到10倍(可能更多).

在Android上发送请求到我的服务器需要几秒钟,而在iOS和浏览器上它几乎是即时的.我确信服务器没有原因.但似乎获得输入流非常慢!

这一行:

in=conn.getInputStream();
Run Code Online (Sandbox Code Playgroud)

是最拖延的,它本身需要几秒钟.

我的目标是从我的服务器获取JSON.我的代码应该在技术上尽可能地优化(并且它可能可以帮助一些人HttpsConnection在同一时间):

protected String getContentUrl(String apiURL)
    {
        StringBuilder builder = new StringBuilder();
        String line=null;
        String result="";
        HttpsURLConnection conn= null;
        InputStream in= null;
        try {
            URL url;
            // get URL content
            url = new URL(apiURL);
            System.setProperty("http.keepAlive", "false");
            trustAllHosts();
            conn = (HttpsURLConnection) url.openConnection();
            conn.setHostnameVerifier(DO_NOT_VERIFY);
            conn.setRequestMethod("GET");
            conn.setRequestProperty(MainActivity.API_TOKEN, MainActivity.ENCRYPTED_TOKEN);
            conn.setRequestProperty("Connection", "close");
            conn.setConnectTimeout(1000);

            in=conn.getInputStream();


            // open the stream and put it into BufferedReader
            BufferedReader br = new BufferedReader(new InputStreamReader(in));

            while ((line=br.readLine())!= …
Run Code Online (Sandbox Code Playgroud)

android json httpconnection

5
推荐指数
0
解决办法
515
查看次数

HttpURLConnection已连接

我正在尝试复制它,openstack swift v1中的复制语句(工作正常):

curl -i $publicURL/GXPrueba/StorageAPI/PruebaStorageCopy.png -X PUT -H "X-Auth-Token:  $token" -H "X-Copy-From: /GXPrueba/StorageAPI/PruebaStorage.png" -H "Content-Length: 0"
Run Code Online (Sandbox Code Playgroud)

像这样:

private void copy(String originContainer, String origin, String destinationContainer, String destination) {
    try {
        URL url = new URL(storageUrl + DELIMITER + destinationContainer + DELIMITER + destination);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setRequestMethod("PUT");
        conn.setRequestProperty("X-Auth-Token", authToken);
        conn.setRequestProperty("X-Copy-From", DELIMITER + originContainer + DELIMITER + origin);
        conn.setRequestProperty("Content-Length", "0");

        if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
            System.err.println("Error while copying the object: " + conn.getResponseCode());
        } …
Run Code Online (Sandbox Code Playgroud)

java openstack-swift httpconnection illegalstateexception

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

UI线程与其他线程之间使用处理程序进行通信

如何在UI线程和后台线程之间进行线程间通信?我想在这里使用通用处理程序概念来更新我的UI.我有如下概念

new Thread(new Runnable() {
         public void run() {
             while (mProgressStatus < 100) {
                 mProgressStatus = doWork();

                 // Update the progress bar
                 mHandler.post(new Runnable() {
                     public void run() {
                         mProgress.setProgress(mProgressStatus);
                     }
                 });
             }
         }
     }).start();
Run Code Online (Sandbox Code Playgroud)

我想使用两个类,一个类包含主线程,另一个类包含后台线程,它们使用相同的处理程序.我该如何实现?我知道这很常见,但我发现很难完全实现.

java multithreading android httpconnection runnable

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

如何关闭HttpClient?为什么 API 中没有 .close() 方法?

我想使用所谓的“自 Java 11 以来的新 HttpClient” java.net.http.HttpClient

对我来说,这非常重要确保 TCP 连接在 HTTP 往返完成后关闭

API上没有可用的.close().disconnect()类似的东西。

无法关闭连接是非常奇怪的,而且也很奇怪为什么预期的行为(发生了什么?连接是否自动关闭?何时?如何?)从未在任何地方记录过,包括Java 简介HTTP 客户端 以及示例和食谱

有小费吗?

java httpclient httpconnection

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