简单的休息api得到调用不工作的android

时间:2014-09-20 07:19:46

标签: android rest

以下代码无效。

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);
}

我使用高级rest客户端测试了url和header,但它确实有用。我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

您应该在后台进行网络操作。例如,在AsyncTask

中运行您的代码

有关详细信息,请参阅 android.os.NetworkOnMainThreadException

以及android manifest.xml文件中的ADD网络权限:

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