1

我有这个代码来提出请求。

@Override
protected Boolean doInBackground(Object... argList) {
/*
* filling all the variables here..
String method = (String) argList[3];
**/
HttpsURLConnection connection = null;
try {
     URL connectURL = new URL(url);
     connection = (HttpsURLConnection) connectURL.openConnection();
     connection.setRequestProperty("connection", "close");
     connection.setRequestMethod(method); // this line 
 connection.setReadTimeout(10000);

/*
* futher code for process GET AND POST Request.
**/
 } catch (IOException e) {
     connection.disconnect();
 } finally{
     connection.disconnect();
   }

例外

04-12 19:30:27.147: WARN/System.err(431): java.net.ProtocolException: Connection already established
04-12 19:30:27.419: WARN/System.err(431):     at java.net.HttpURLConnection.setRequestMethod(HttpURLConnection.java:429)
04-12 19:30:27.447: WARN/System.err(431):     at org.apache.harmony.luni.internal.net.www.protocol.https.HttpsURLConnectionImpl.setRequestMethod(HttpsURLConnectionImpl.java:127)
04-12 19:30:27.487: WARN/System.err(431):     at com.app.services.AppServiceManager.doInBackground(AppServiceManager.java:297)
04-12 19:30:27.526: WARN/System.err(431):     at com.app.services.AppServiceManager.doInBackground(AppServiceManager.java:1)
04-12 19:30:27.559: WARN/System.err(431):     at android.os.AsyncTask$2.call(AsyncTask.java:185)
04-12 19:30:27.617: WARN/System.err(431):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
04-12 19:30:27.636: WARN/System.err(431):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
04-12 19:30:27.716: WARN/System.err(431):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
04-12 19:30:27.751: WARN/System.err(431):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
04-12 19:30:27.798: WARN/System.err(431):     at java.lang.Thread.run(Thread.java:1096)
4

1 回答 1

2

恕我直言,您最好使用 Apache HTTP 类。它们只是比 Java 具有的烘焙 URL 更有意义,并且直接在 Android API 中有一个端口:

http://developer.android.com/reference/org/apache/http/package-summary.html

然后我会将它传递给您的 AsyncTask,因为它是超类:

HttpUriRequest request = new HttpPost(uri):
// ... configure

或者

HttpUriRequest request = new HttpGet(uri)
// ... configure

您的 AsyncTask 看起来像:

new AsyncTask<HttpUriRequest, Void, ResultClass>(){

    public ResultClass doInBackground(HttpUriRequest... requests) {

        HttpClient client = new DefaultHttpClient();
        HttpResponse response = client.execute(requests[0]);

        // handle the response
        return instanceOfResultClass;
    }

    // ... 

}.execute(request);

你明白了,希望。:)

于 2012-04-12T15:47:23.890 回答