简体   繁体   中英

Android HTTP GET doesn't work

I know Java but unfortunately chosen Basic4Android for Android Development. After working over an year I realized I should move in native solution. So my question might be silly but I need your advice to solve it.

My goal is to retrieve data from a GET request. I've tried tons of android http client tutorials over internet but failed with each tutorial. I'm just going to share one here so that you can help me to fix. When I'm clicking on the button, nothing is happening without tons of error message in logcat window.

Main Class is here for a quick review:

public class MainActivity extends Activity implements OnClickListener {

    private Button Test;

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

        Test = (Button) findViewById(R.id.Test);
        Test.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.Test){
            try {
                HttpClient client = new DefaultHttpClient();  
                String getURL = "http://www.google.com";
                HttpGet get = new HttpGet(getURL);
                HttpResponse responseGet = client.execute(get);  
                HttpEntity resEntityGet = responseGet.getEntity();  
                if (resEntityGet != null) {  
                    // do something with the response
                    String response = EntityUtils.toString(resEntityGet);
                    Log.i("GET RESPONSE", response);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            }
        }
    }

And the whole project is here: https://dl.dropboxusercontent.com/u/15625012/TestHttp.zip

I'll really appreciate any sort of help/advice.

First- always post the errors in logcat here, we almost always need them to fix the problem.

But here it's easy- you can't do network IO on the main thread. You need to run it on an AsyncTask or a Thread instead.

    try {
        URL url = new URL(urlstr);
        HttpsURLConnection connection = 
                  (HttpsURLConnection)url.openConnection();
        connection.setReadTimeout(6000);
        connection.setRequestMethod("GET");
        connection.setRequestProperty("User_agent", "android");
        OutputStream os = connection.getOutputStream();
        //os.write(buffer);

        InputStream is = connection.getInputStream();

    } catch (MalformedURLException e) 
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }catch (Exception e) {
        // TODO: handle exception
    }

you are currently doing a network access in your main UI thread (Button click function). Android does not allow long operations such as network access in the main thread UI thread of the app. You need to do this asynchronously in a separate thread. You can use built in Async Class for this purpose.

Here is a sample code i wrote

public class Sample extends Activity 
{   
private ProgressDialog progress_dialog;

@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sample);

    progress_dialog = new ProgressDialog(this);
}

public void MyButtonClick(View view)
{
        EditText usernameEditText = (EditText)findViewById(R.id.sample_username);
        String username = usernameEditText.getText();

        String URL = "http://SOME_WEBSITE?Username=" + username;

        progress_dialog.setMessage("Loading. Please wait...");
    progress_dialog.setCancelable(false);
    progress_dialog.show();

    new SampleAsynThread().execute(URL);
}

private class SampleAsynThreadextends AsyncTask <String, Void, String> 
{
        protected String doInBackground(String... urls)
        {
            // make your request here
            return "Response";
        }

        protected void onPostExecute(String result) 
        { 
            // show response on ui   
            progress_dialog.dismiss();
        }
    }

protected void onDestroy()
{
    progress_dialog.dismiss();
    super.onDestroy();
}

@Override
protected void onPause()
{
    progress_dialog.dismiss();
    super.onPause();
}

}

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