Android - HttpClient只能运行一次

时间:2013-05-20 09:54:37

标签: android httpclient

我正在后台打开一个网址,因为当他去link它'喜欢'文章3020

我正在使用HttpClient执行此操作:

public static class LoadURL extends AsyncTask<Void, Integer, Void>{

              @Override
              protected Void doInBackground(Void... params) {
                    try {
                second_client = new DefaultHttpClient();  
                String getURL = "http://website.com/" + id_string + "/like/";
                HttpGet get = new HttpGet(getURL);
                HttpResponse responseGet = second_client.execute(get, cookieStuff);

              Log.i("Response", String.valueOf(response.getStatusLine().getStatusCode()));  

            } catch (Exception e) {
                e.printStackTrace();
            }
               return null;

              }

              @Override
              protected void onPostExecute(Void result) {
               super.onPostExecute(result);
               Toast.makeText(AFragment.context, "Article liked", Toast.LENGTH_LONG).show();  
              }
        }

问题是有大量文章(3020-3021-3022等),因此用户会多次点击“喜欢”按钮。这意味着LoadURL任务已完成多次,但它仅在第一次运行。之后的所有时间都需要5分钟以上。

有人知道如何解决这个问题吗?或者有比使用HttpClient更好的方法吗?

2 个答案:

答案 0 :(得分:4)

您确定网络服务器运行良好吗? 1.你应该做的第一件事是创建一个DefaultHttpsClient的静态实例并且每次使用相同的实例,它应该运行良好,我已经使用了很多次。 2.看看volley,这是谷歌发布的一个新的网络库

答案 1 :(得分:0)

您只需要实例化一次客户端并使用ThreadedClientConnManager

重复使用它
HttpClient mClient;
 HttpParams params = new BasicHttpParams();
        ConnManagerParams.setMaxTotalConnections(params, 100);
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        schemeRegistry.register(new Scheme ("https", SSLSocketFactory.getSocketFactory(), 443));

        ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);

        mClient = new DefaultHttpClient(cm, params);

现在只需重用客户端

public static class LoadURL extends AsyncTask<Void, Integer, Void>{

              @Override
              protected Void doInBackground(Void... params) {
                    try {

                String getURL = "http://website.com/" + id_string + "/like/";
                HttpGet get = new HttpGet(getURL);
                HttpResponse responseGet = mClient.execute(get, cookieStuff);

              Log.i("Response", String.valueOf(response.getStatusLine().getStatusCode()));  

            } catch (Exception e) {
                e.printStackTrace();
            }
               return null;

              }

              @Override
              protected void onPostExecute(Void result) {
               super.onPostExecute(result);
               Toast.makeText(AFragment.context, "Article liked", Toast.LENGTH_LONG).show();  
              }
        }