2012-09-26 132 views
-2

我想excecute一些职位要求,我审查的网站,因为它有一些敏感的数据..那么这里的代码:HTTP POST请求崩溃

 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

我不是Android开发人员,但一个简单的谷歌搜索“的Android NetworkOnMainThreadException”显示,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调用)主线程的工作,因为它会阻止主动画循环。

+0

我明白了,谢谢! – idish