0

我尝试在 Web 服务器上发送 JSON 数据并通过这种方法获得响应。

public JSONObject postOnServer(JSONObject json) {

    HttpResponse response;
    JSONObject res = null;

    HttpClient httpclient = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 10000);
    HttpPost httpPost = new HttpPost(PATH);

    try {

        //StringEntity stringEntity = new StringEntity("json", String.valueOf(json));
        ByteArrayEntity postMessage = new ByteArrayEntity(json.toString().getBytes("UTF8"));
        httpPost.setEntity(postMessage);
        response = httpclient.execute(httpPost);

        if (response.getStatusLine().getStatusCode() == 200) {

            InputStream instream = response.getEntity().getContent();
            try {
                res = new JSONObject(convertStreamToString(instream));
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                Log.i("Response JSON", e.toString());
            }

        } else {

            res = new JSONObject();
            try {
                res.put("error", "Unable to load page.");
            } catch (JSONException e) {
                // TODO Auto-generated catch block
            }

        }
    } catch (IOException ex) {

        Log.i("Connection.postOnServer", "1.try exception: "+ex);
        res = new JSONObject();
        try {
            res.put("error", "Synchronization is not enable: Connection has aborted.");
        } catch (JSONException e) {
            Log.i("Connection.postOnServer", "put exception: "+e);
        }

    }

    return res;
}

但总是response = httpclient.execute(httpPost);以这个例外结束

05-24 10:58:51.635: E/AndroidRuntime(4709): FATAL EXCEPTION: main
05-24 10:58:51.635: E/AndroidRuntime(4709): android.os.NetworkOnMainThreadException
05-24 10:58:51.635: E/AndroidRuntime(4709):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
05-24 10:58:51.635: E/AndroidRuntime(4709):     at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
05-24 10:58:51.635: E/AndroidRuntime(4709):     at libcore.io.IoBridge.connectErrno(IoBridge.java:138)
05-24 10:58:51.635: E/AndroidRuntime(4709):     at libcore.io.IoBridge.connect(IoBridge.java:112)
05-24 10:58:51.635: E/AndroidRuntime(4709):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
05-24 10:58:51.635: E/AndroidRuntime(4709):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
05-24 10:58:51.635: E/AndroidRuntime(4709):     at java.net.Socket.connect(Socket.java:842)
05-24 10:58:51.635: E/AndroidRuntime(4709):     at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
05-24 10:58:51.635: E/AndroidRuntime(4709):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
05-24 10:58:51.635: E/AndroidRuntime(4709):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
05-24 10:58:51.635: E/AndroidRuntime(4709):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
05-24 10:58:51.635: E/AndroidRuntime(4709):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
05-24 10:58:51.635: E/AndroidRuntime(4709):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
05-24 10:58:51.635: E/AndroidRuntime(4709):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
05-24 10:58:51.635: E/AndroidRuntime(4709):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)

有人知道,如何解决?如果我使用 catch(IOException),在口渴的尝试中,应用程序将被破坏。如果我使用 catch(Exception) 应用程序继续不采取任何行动。我应该怎么做才能发送数据?

4

1 回答 1

2

Android 不允许您在用户界面线程上运行网络请求。这是为了阻止请求在执行时阻塞界面。您需要在单独的线程中执行请求。这是一个例子:

new Thread(new Runnable() {
    //Thread to stop network calls on the UI thread
    public void run() {
        //Request the HTML
        try {
            HttpParams httpParameters = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParameters, TIMEOUT_CONNECTION);
            HttpConnectionParams.setSoTimeout(httpParameters, TIMEOUT_SOCKET);

            HttpClient client = new DefaultHttpClient(httpParameters);
            HttpGet request = new HttpGet(getString(R.string.url));
            HttpResponse response = client.execute(request);

            //Do something with the response
        }
        catch (IOException e) {
            Log.e("Tag", "Could not get HTML: " + e.getMessage());
        }
    }
}).start();
于 2012-05-24T09:34:21.680 回答