简体   繁体   中英

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. Am I missed anything?

You should do networking operations in background.For eg run your code in AsyncTask

For more info see android.os.NetworkOnMainThreadException

and also ADD network permission in android manifest.xml file:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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