0

我尝试制作一个支持 AsyncTask 的类,但我失败了。后来我制作了这个类的超类,并在我的主类中添加了这个:

//subclass of the superclass CustomHttpClient
CustomHttpClient2 cl= new CustomHttpClient2();
cl.execute();
response = cl.executeHttpPost("http://ironis.dyndns.org/aeglea/android/log.php", postParameters);

错误消息是 android.os.NetworkOnMainThreadException

我要转换的类是this(我在sdk 7中使用它,但我移动到14,现在它失败了)

public class CustomHttpClient2 (extends CustomHttpClient)<<I used it without this {

 public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
    private static HttpClient mHttpClient;


    /**
     * Get our single instance of our HttpClient object.
     *
     * @return an HttpClient object with connection parameters set
     */
    private static HttpClient getHttpClient() {
        if (mHttpClient == null) {
            mHttpClient = new DefaultHttpClient();
            final HttpParams params = mHttpClient.getParams();
            HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
            HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
            ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
        }
        return mHttpClient;
    }

    /**
     * Performs an HTTP Post request to the specified url with the
     * specified parameters.
     *
     * @param url The web address to post the request to
     * @param postParameters The parameters to send via the request
     * @return The result of the request
     * @throws Exception
     */
    public JSONObject executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
        BufferedReader in = null;
        HttpEntity he=null;
        JSONObject jo=null;

        try {
            HttpClient client = getHttpClient();
            HttpPost request = new HttpPost(url);
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
            request.setEntity(formEntity);
            HttpResponse response = client.execute(request);
            //mine
            he=response.getEntity();
            jo=new JSONObject(EntityUtils.toString(he));
            //end mine

            return jo;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * Performs an HTTP GET request to the specified url.
     *
     * @param url The web address to post the request to
     * @return The result of the request
     * @throws Exception
     */
    public static String executeHttpGet(String url) throws Exception {
        BufferedReader in = null;
        try {
            HttpClient client = getHttpClient();
            HttpGet request = new HttpGet();
            request.setURI(new URI(url));
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();

            String result = sb.toString();
            return result;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

我使用 CustomHttpClient 的另一个类如下

public class CustomHttpClient extends AsyncTask<HttpClient,String,String> {
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
private static HttpClient mHttpClient;



protected HttpClient doInBackground(String... params) {
    if (mHttpClient == null) {
        mHttpClient = new DefaultHttpClient();
        final HttpParams params1 = mHttpClient.getParams();
        HttpConnectionParams.setConnectionTimeout(params1, HTTP_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params1, HTTP_TIMEOUT);
        ConnManagerParams.setTimeout(params1, HTTP_TIMEOUT);
    }
    return mHttpClient;
}



@Override
protected String doInBackground(HttpClient... params) {
    // TODO Auto-generated method stub
    return null;
}




}

对我有爱吗?

4

3 回答 3

2

您的异步任务可能如下所示:

public class CustomHttpTask extends AsyncTask<CustomHttpClient2,String,String> {
   public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds


   @Override
   protected String doInBackground(HttpClient... params) {
       //subclass of the superclass CustomHttpClient
       CustomHttpClient2 cl= params[0];
       response = cl.executeHttpPost("http://ironis.dyndns.org/aeglea/android/log.php", postParameters);

        // say, you need response string back

        return response.toString();
}

    @Override
    protected void onPostExecute(String result) {
        showDialog("Downloaded " + result + " response");
    }
}

并通过以下方式调用它:

CustomHttpTask task = new CustomHttpTask();
task.execute(new CustomHttpClient2());

而且,Android 以正确的方式抛出 NetworkOnMainThreadException 然后您尝试在 UI 线程上执行网络请求,以帮助您避免连接缓慢的 ANR。

于 2012-08-24T02:28:35.753 回答
0

我认为这可能与不覆盖正确的doInBackground方法有关。相反,您使用不同的参数类型重载。在您的类定义(例如)中切换 HttpClient 和 String...extends AsyncTask<String,String,HTTPClient>以便能够传递正确的参数并返回正确的结果。

[编辑]我不确定我是否理解你问题的本质,但我的观点是唯一将在一个单独的线程中执行的东西(你必须把你的 IO 放进去)是正确doInBackground方法中的东西。

于 2012-08-24T02:22:07.333 回答
0

谁有类似的问题,我会发布我的解决方案。

我修改了@sandrstar 的解决方案,我做到了

public class CustomHttpTask extends AsyncTask<Object,String,JSONObject> {
   public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
   private JSONObject response = null;

   @Override
   protected JSONObject doInBackground(Object... params) {
       //subclass of the superclass CustomHttpClient
       //CustomHttpClient cl= (CustomHttpClient) params[0];
       String url = (String) params[0];
       ArrayList<NameValuePair> postParameters = (ArrayList<NameValuePair>) params[1];
    try {
        response = CustomHttpClient.executeHttpPost(url, postParameters);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

        // say, you need response string back

        return response;
}

    @Override
    protected void onPostExecute(JSONObject result) {

    }
    public JSONObject getval(){
        return response;
    }

}

现在我可以在不同的网址中发布多个帖子。问题是我想要一个 json 对象。有2种方式。要么像我一样创建一个函数。或者使用 AsyncTask 的 get() 函数

CustomHttpTask asdf = new CustomHttpTask();
response = asdf.execute("http://192.168.1.4/aeglea/android/log.php", postParameters).get();

首先执行,完成后执行获取部分。;)

于 2012-08-24T22:38:50.670 回答