http post请求崩溃

时间:2012-09-26 18:17:46

标签: c# java http request

我正在尝试优先发布一些帖子请求,我对该网站进行了审查,因为它有一些敏感数据..这里是代码:

        HttpClient httpclient = new DefaultHttpClient();   
    HttpPost httppost = new HttpPost("http://www.someaddress.com"); 
        // Add your data   
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);   
        nameValuePairs.add(new BasicNameValuePair("sdata", ""));

        try {
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8));
                Log.d("MyTag", "works till here.");
                try {
                    HttpResponse response = httpclient.execute(httppost);
                   // String responseBody = EntityUtils.toString(response.getEntity());
             //       Log.d("MyTag", responseBody);
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

它在那条线上崩溃了:

  HttpResponse response = httpclient.execute(httppost);

这里的logcat对我来说什么都没说: http://pastebin.com/F0YAiNLD

可能是什么问题?为什么会崩溃? 我正在尝试将这个C#代码翻译成JAVA。 C#代码有效,但JAVA代码不行。

这是C#代码:

        System.Text.UTF8Encoding encoding=new System.Text.UTF8Encoding();
    string pData = "";
    byte[] sdata = encoding.GetBytes(pData);
    HttpWebRequest request = new HttpWebRequest(new Uri("http://www.someaddress.com"));
    request.ContentType="application/x-www-form-urlencoded";
    request.ContentLength = sdata.Length;
    Stream nStream=request.GetRequestStream();
    nStream.Write(sdata,0,sdata.Length);
    nStream.Close();
    HttpWebResponse response = 
    (HttpWebResponse) request.GetResponse();

1 个答案:

答案 0 :(得分:1)

我不是Android开发人员,但对“Android NetworkOnMainThreadException”的简单Google搜索显示this exception is thrown when you attempt to do network actions on the main event thread(该名称非常具有自我描述性),以及instead you should be making these type of network calls on a background thread

通常在GUI应用程序中,在可以阻止的主线程(例如网络HTTP调用)中工作是个坏主意,因为它会阻止主动画循环。