2014-06-06 76 views
0

我正在使用此代碼,但它在try-catch中捕獲錯誤。哪裏出錯?如何在Android中使用HttpGet請求?

當我打印錯誤時,content.setText(ex.getMessage());爲空。

下面是相關代碼:

public class MainActivity extends Activity { 

    TextView content; 
    EditText fname, email; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 

     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     content = (TextView) findViewById(R.id.content); 
     Button saveme = (Button) findViewById(R.id.save); 
     saveme.setOnClickListener(new Button.OnClickListener() { 
      public void onClick(View v) { 
       Toast.makeText(getBaseContext(), "Please wait, connecting to server.", Toast.LENGTH_LONG).show(); 

       try { 
        String loginValue = URLEncoder.encode("ffa", "UTF-8"); 
        String fnameValue = URLEncoder.encode("fdsfdb", "UTF-8"); 

        HttpClient Client = new DefaultHttpClient(); 
        String URL = "http://mysite/app.php?a=" + loginValue + "&b=" + fnameValue; 

        try { 
         String SetServerString; 
         HttpGet httpget = new HttpGet(URL); 
         ResponseHandler<String> responseHandler = new BasicResponseHandler(); 
         SetServerString = Client.execute(httpget, responseHandler); 
         content.setText(SetServerString); 
        } catch (Exception ex) { 
         content.setText(ex.getMessage()); 
        } 
       } catch (UnsupportedEncodingException ex) { 
        content.setText(ex.getMessage()); 
       } 
      } 
     }); 
    } 
} 
+0

你在uithread運行網絡操作 – Raghunandan

+0

可能重複[android.os.NetworkOnMainThreadException](http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception) – 323go

回答

0

我想你NetworkOnMainThreadException。您應該在後臺線程上執行網絡通信。考慮使用IntentService或AsyncTask。

0

我對Nickolai有同樣的看法。

解決方法:

if (android.os.Build.VERSION.SDK_INT > 9) { 
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
    StrictMode.setThreadPolicy(policy); 
} 

使用上面的代碼,只有當你爲自己編寫代碼。


如果您的應用程序是爲其他人制作的,則需要更好的方法。

更好的辦法:

您應該使用一個手柄來訪問http請求,more info in developer.android.com

0

我用這個自己:

ByteArrayOutputStream out = new ByteArrayOutputStream(); 
response.getEntity().writeTo(out); 
out.close(); 
String responseString = out.toString();