Android DefaultHttpClient()发布请求

时间:2013-05-25 22:45:20

标签: java android

我想发送一个带有两个参数的POST请求,从JsonObject到一个python API,它的响应为True或False,但它根本不起作用......

我的代码:

// Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://10.30.0.47:8080/getsession");

    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("Name", db.getString("name")));
        nameValuePairs.add(new BasicNameValuePair("Passwort", db.getString("passwort")));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        HttpResponse res = httpclient.execute(httppost);
        Log.v("Response", res.toString());

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }

LogCat Output: http://pastebin.com/GL54UFGG

1 个答案:

答案 0 :(得分:4)

在您的堆栈跟踪中,它清楚地说明:

05-25 20:42:05.455: E/AndroidRuntime(29706): Caused by: android.os.NetworkOnMainThreadException

这意味着您正在MainUI线程中执行网络加载,您必须使用单独的线程进行网络工作,最好使用AsyncTask