Android: IllegalStateException in HttpGet

北战南征 提交于 2019-11-27 09:51:14
Ali

I think you need to use .addHeader for HttpGet, for example to transfer data in Json format:

public class Client {

    private String server;

    public Client(String server) {
        this.server = server;
    }

    private String getBase() {
        return server;
    }

    public String getBaseURI(String str) {
        String result = "";
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet getRequest = new HttpGet(getBase() + str);
            getRequest.addHeader("accept", "application/json");
            HttpResponse response = httpClient.execute(getRequest);
            result = getResult(response).toString();
            httpClient.getConnectionManager().shutdown();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    private StringBuilder getResult(HttpResponse response) throws IllegalStateException, IOException {

        StringBuilder result = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())), 1024);
        String output;
        while ((output = br.readLine()) != null) 
            result.append(output);
        return result;
    }
}

I also suggest you to use timeoutConnection (until a connection is established) and timeoutSocket (timeout for waiting for data.) for more information look at: Java jersey RESTful webservice requests

Also note that You need to implement your network connection on a separate thread for API level 11 or greater.

you have to add the http:// to address, in order to get it work. Avoid the use of URLEncoder, if you do.

When you do this:

HttpGet getData = new HttpGet(this.address);

what exactly is this.address? I'm assuming it is a String, if so it needs to look like this:

String address = "http://www.google.com/path/to/document";

You've probably done this:

String address = "google.com";

This is your Host error You are passing "www.host.com" instead you have to pass "http://www.w3schools.com"

reference post is here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!