3

我在后台打开一个网址,因为当转到链接 时它“喜欢”文章 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 更好的方法?

4

2 回答 2

4

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

于 2013-05-20T10:03:48.207 回答
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();  
              }
        }
于 2013-05-20T10:14:44.223 回答