2012-09-26 184 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