Using HttpGet on Android

2019-04-17 04:20发布

问题:

I can't understand, why I can't get http response without error from any url.

   package de.vogella.android.asynctask;
import java.io.IOException;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Toast;

public class SimpleWebGrab extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        grabURL("http://android.com");
    }

    public void grabURL(String url) {
        //new GrabURL().execute(url);

        GrabURL grabURL = new GrabURL(); // Создаем экземпляр
        grabURL.execute(url); // запускаем
    }

    private class GrabURL extends AsyncTask<String, Void, Void> {
        private final HttpClient Client = new DefaultHttpClient();
        private String Content;
        private String Error = null;
        private ProgressDialog Dialog = new ProgressDialog(SimpleWebGrab.this);

        protected void onPreExecute() {
            Dialog.setMessage("Загрузка данных..");
            Dialog.show();
        }

        protected Void doInBackground(String... urls) {
            try {
                HttpGet httpget = new HttpGet(urls[0]);
                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                Content = Client.execute(httpget, responseHandler);
            } catch (ClientProtocolException e) {
                Error = e.getMessage();
                cancel(true);
            } catch (IOException e) {
                Error = e.getMessage();
                cancel(true);
            }

            return null;
        }

        protected void onPostExecute(Void unused) {
            Dialog.dismiss();
            if (Error != null) {
                Toast.makeText(SimpleWebGrab.this, Error, Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(SimpleWebGrab.this, "Источник: " + Content, Toast.LENGTH_LONG).show();
            }
        }

    }
}

I get error on this lines:

} catch (IOException e) {
        Error = e.getMessage();
        cancel(true);
    }

Error text is:

Connection to http://android.com refused

It doesn't matter which url I use. All the same. On this line after Step Into I get Class file editor: "source not found" message while debugging, but app doesn't crash if I press Run:

HttpGet httpget = new HttpGet(urls[0]);

Is it the reason of connection refused? If yes, how to fix it? Thanks in advance.

回答1:

This is just a guess, but maybe this is because you are running the request on the main thread? You should usually prepare a background thread that will run this code for you.

The code looks approximately like this:

Runnable r = new Runnable() { 
  void run()
  {
       // enter here httpget code
  }
}

new Handler().post(r);


回答2:

Did you added permission "android.permission.INTERNET" to your AndroidManifest.xml?



回答3:

I found out, that this is a common problem, when there is no internet on emulator. I solved my problem by typing -http-proxy xxx.xx.111.1:3128 in Run->Run Configurations->Target->Additional Command Line Options(which is at the bottom, need to scroll). This is where I found a solution: http://www.gitshah.com/2011/02/android-fixing-no-internet-connection.html