0

在进行 HttpPost 调用时,我在我的 Android 项目中遇到了一个异常,我不知道为什么。这是进行网络调用的方法的开始:

try {


        this.httpClient = new DefaultHttpClient();
        httpPost = new HttpPost(url);

        if (json != null && json != "") {
            httpPost.setEntity(new ByteArrayEntity(json.getBytes("UTF8")));
            httpPost.setHeader("Content-type", "application/json");
            if(token!=null) {
                //httpPost.setHeader("Authorization", "Basic VEU5SFNVNWZWRmxRUlY5RFZWTlVUMDFGVWpwcWFXMXRlV1JoWjJobGNrQm5iV0ZwYkM1amIyMDZNVEV4TVE9PQ==");
                httpPost.setHeader("Authorization", "Basic " + token);
            }
        }



        HttpParams httpParameters = new BasicHttpParams();
        // Set the timeout in milliseconds until a connection is established.
        // The default value is zero, that means the timeout is not used. 
        int timeoutConnection = 15000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        // Set the default socket timeout (SO_TIMEOUT) 
        // in milliseconds which is the timeout for waiting for data.
        int timeoutSocket = 15000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
        httpClient.setParams(httpParameters);


        httpResponse = httpClient.execute(httpPost);

最后一行是捕获异常的地方。我尝试注销 exception.getMessage(),但那是空的。这是堆栈回溯:

java.net.PlainSocketImpl.read(PlainSocketImpl.java:492)
java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:46)
java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:241)
org.apache.http.impl.io.AbstractSessionInputBuffer.fillBuffer(AbstractSessionInputBuffer.java:103)
org.apache.http.impl.io.AbstractSessionInputBuffer.readLine(AbstractSessionInputBuffer.java:191)
org.apache.http.impl.conn.DefaultResponseParser.parseHead(DefaultResponseParser.java:82)
org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:174)
org.apache.http.impl.AbstractHttpClientConnection.receiveResponseHeader(AbstractHttpClientConnection.java:180)
org.apache.http.impl.conn.DefaultClientConnection.receiveResponseHeader(DefaultClientConnection.java:235)
org.apache.http.impl.conn.AbstractClientConnAdapter.receiveResponseHeader(AbstractClientConnAdapter.java:259)
org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:279)
org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:121)
org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:428)
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:670)
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:509)
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
com.arcmobileapp.web.WebServices.getResponse(WebServices.java:106)
com.arcmobileapp.web.WebServices.createReview(WebServices.java:601)
com.arcmobileapp.web.SubmitReviewTask.performTask(SubmitReviewTask.java:59)
com.arcmobileapp.web.SubmitReviewTask.doInBackground(SubmitReviewTask.java:47)
com.arcmobileapp.web.SubmitReviewTask.doInBackground(SubmitReviewTask.java:1)
android.os.AsyncTask$2.call(AsyncTask.java:287)
java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
java.util.concurrent.FutureTask.run(FutureTask.java:137)
android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
java.lang.Thread.run(Thread.java:856)

知道什么可能导致异常吗?它不是每次都发生,它似乎是间歇性的(网络?)。

提前致谢。

4

2 回答 2

1

java.net.PlainSocketImpl当您尝试连接的端口上没有服务侦听时,通常会发生此异常。

重新检查以下三件事

1) 您尝试连接的主机名和端口。

2)服务器端已成功开始正确收听。

3)没有防火墙阻止连接。

于 2013-10-20T15:21:18.773 回答
0

测试这段代码:

public class HttpConnectionTask
{
    public static final int RESPONSE_OK = 0;
    public static final int RESPONSE_ERROR = 1;    

    private String body = null;
    private String strUrl;
    private int responsCode;
    private List<NameValuePair> postData = null;

    public HttpConnectionTask(String strUrl)
    {
        this.strUrl = strUrl;
    } 

    public HttpConnectionTask(String strUrl, List<NameValuePair> postData)
    {
        this.strUrl = strUrl;
        this.postData = postData;
    } 

    public void run() 
    {               
        try
        {           
            this.responsCode = RESPONSE_OK;

            HttpClient client = new DefaultHttpClient(); 
            HttpResponse response = null;

            if(this.postData == null)
            {
                HttpGet get = new HttpGet(this.strUrl);             
                response = client.execute(get); 
            }
            else
            {
                HttpPost postMethod = new HttpPost(this.strUrl);
                postMethod.setEntity(new UrlEncodedFormEntity(this.postData, "UTF-8"));
                response = client.execute(postMethod);
            }

            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            this.body = "";

            char[] dataChunk = new char[1024];            
            StringBuffer dataBuffer = new StringBuffer();

            int readSize = 0;

            while((readSize = rd.read(dataChunk)) >= 0)
            {                
                dataBuffer.append(dataChunk, 0, readSize);                
            }

            this.body = dataBuffer.toString().trim();                       
        }        
        catch (Exception ex)
        {            
            this.responsCode = RESPONSE_ERROR;
        }                                               
    }

    public String getBody()
    {
        return this.body;
    }

    public int getResponse()
    {
        return this.responsCode;
    }
}

并使用这个类:

String url = "Your url" + "?exam1=1"; //for get data                                                    

List<NameValuePair> postData = new ArrayList<NameValuePair>();          
postData.add(new BasicNameValuePair("test1", "123")); //for post data
postData.add(new BasicNameValuePair("test2", "456")); //for post data

HttpConnectionTask httpPost = new HttpConnectionTask(url, postData);
httpPost.run();
于 2013-10-20T15:48:34.840 回答