2013-07-20 59 views
0

我正在嘗試向本地NodeJS服務器發出一個簡單的GET請求以獲取一些JSON對象。我改變了請求,所以它作爲一個AsyncTask而不是在UI線程中發生。但我仍然無法實現它的工作。這段代碼看起來是否正確?對不起,Java還不好。無法獲取適用於Android的GET請求

package com.dd.relay; 

import com.dd.relay.HttpRequest; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.net.HttpURLConnection; 
import java.net.URL; 

import android.app.ListActivity; 
import android.content.Context; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.Menu; 
import android.widget.TextView; 
import android.widget.Toast; 

public class MainActivity extends ListActivity { 
    public final static String EXTRA_MESSAGE = "com.dd.relay.MESSAGE"; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 

      // We'll define a custom screen layout here (the one shown above), but 
      // typically, you could just use the standard ListActivity layout. 
      setContentView(R.layout.activity_main); 


      // Make a GET request for data 
      String url = "http://localhost.com/contacts"; 
      String res = null; 
      try { 
       HttpRequest request = new HttpRequest(); 
       request.execute(new URL(url)); 

       Log.v(EXTRA_MESSAGE, res); 
      } catch (Exception e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

      TextView textView = (TextView) findViewById(R.id.textv); 
      Context context = this.getApplicationContext(); 
      Toast mytoast = Toast.makeText(context, res, Toast.LENGTH_LONG); 
      mytoast.show(); 
      textView.setText(res); 
      // Create list for contacts 
      /* List<Map<String, RelayContact>> data = null; 


      // Now create a new list adapter bound to the cursor. 
      // SimpleListAdapter is designed for binding to a Cursor. 
      ListAdapter adapter = new SimpleAdapter(this, data, 0, new String[] {"First", "Number"}, new int[] {android.R.id.text1, android.R.id.text2}); // Parallel array of which template objects to bind to those columns. 

      // Bind to our new adapter. 
      this.setListAdapter(adapter);*/ 
} 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.main, menu); 
     return true; 
    } 




} 

這裏是我的自定義的HttpRequest的AsyncTask類

package com.dd.relay; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.net.HttpURLConnection; 
import java.net.URL; 

import android.os.AsyncTask; 

public class HttpRequest extends AsyncTask<URL, Void, Void> { 

    protected String doInBackground(URL url) throws Exception { 

      HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 


      if (conn.getResponseCode() != 200) { 
      throw new IOException(conn.getResponseMessage()); 
      } 

      // Buffer the result into a string 
      BufferedReader rd = new BufferedReader(
       new InputStreamReader(conn.getInputStream())); 
      StringBuilder sb = new StringBuilder(); 
      String line; 
      while ((line = rd.readLine()) != null) { 
      sb.append(line); 
      } 
      rd.close(); 

      conn.disconnect(); 
     return sb.toString(); 


    } 

    protected void onProgressUpdate(Integer progress) { 

    } 

    protected void onPostExecute(String result) { 
     System.out.println(result); 
    } 

    @Override 
    protected Void doInBackground(URL... arg0) { 
     // TODO Auto-generated method stub 
     return null; 
    } 


} 
+0

任何特定類型的異常? –

+0

我不認爲Android系統會在UI線程中發生這樣的連接。如何製作一個AsyncTask? –

+0

謝謝你們..我用AsyncTask類更新了我的代碼,但仍然無法讓它正常工作..任何想法? –

回答

2

Android不允許在UI線程上進行網絡通信。 Android提供了一個名爲AsyncTask的類,用於這種交互。請參閱解決此鏈接的詳細信息,以及一個選項(這可能是你想要的):

How to fix android.os.NetworkOnMainThreadException?

,或者您也可以創建該職位到UI線程使用擴展Thread或實現Runnable的自定義類一個Handler

+0

好的非常感謝。那個例外恰恰是被拋出的 –

+0

當然,祝你好運! – Scott

+0

我的編輯看起來如何? –

0

嘗試此鏈接,希望使用全給你: -

Verifying login details via http get : Android

public class LongOperation extends AsyncTask<String, Void, String> { 

     @Override 
     protected String doInBackground(String... params) { 
       // call function 
       login(userName, password); 
       return null; 
     }   

     @Override 
     protected void onPostExecute(String result) {    
     } 

     @Override 
     protected void onPreExecute() { 
     } 

     @Override 
     protected void onProgressUpdate(Void... values) { 
     } 
    }