2014-09-20 81 views
0

下面的代碼不起作用。簡單的休息api讓電話不工作android

String url = "http://my/url/username/pswd"; 
String result = ""; 

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    TextView tv; 
    tv = (TextView) findViewById(R.id.text1); 

    HttpClient httpclient = new DefaultHttpClient(); 
    HttpGet request = new HttpGet(url); 
    request.addHeader("apikey", "DeveloperWy7ayxR"); 
    request.addHeader("Content-Type","application/json"); 

    ResponseHandler handler = new BasicResponseHandler(); 
    try { 
     result = httpclient.execute(request, handler); 
    } catch (ClientProtocolException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    httpclient.getConnectionManager().shutdown(); 
    Log.i("myLog", result); 

    tv.setText(result); 
} 

我使用高級休息客戶端測試了url和headers,它工作正常。我錯過了什麼?

回答

0

您應該在後臺進行聯網操作。運行AsyncTask

代碼欲瞭解更多信息請參閱 android.os.NetworkOnMainThreadException

,並添加網絡權限android的manifest.xml文件:

<uses-permission android:name="android.permission.INTERNET"/> 
+0

我已經添加權限 – SGG 2014-09-20 07:47:55

+0

@SGG那麼你是什麼意思不工作?請詳細說明。 – 2014-09-20 07:48:42

+0

現在我正在嘗試與asynktask。如果它也不起作用,我會更新我的問題 – SGG 2014-09-20 07:51:31