简体   繁体   English

简单的REST API获取呼叫无法正常工作的Android

[英]simple rest api get call not working android

The below code is not working. 以下代码无法正常工作。

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

I tested url and headers with advanced rest client, it worked. 我使用高级rest客户端测试了url和标头,它起作用了。 Am I missed anything? 我错过了什么吗?

You should do networking operations in background.For eg run your code in AsyncTask 您应该在后台进行网络操作。例如,在AsyncTask中运行代码

For more info see android.os.NetworkOnMainThreadException 有关更多信息,请参见android.os.NetworkOnMainThreadException

and also ADD network permission in android manifest.xml file: 并在android manifest.xml文件中添加网络权限:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM