如何打败这个java.net.ProtocolException:已在Android中建立连接

时间:2012-04-12 15:18:29

标签: java android

我有这个代码提出请求。

@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)

1 个答案:

答案 0 :(得分: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);

希望你能得到这个想法。 :)