Aljosha
Aljosha

Reputation: 222

cannot load text from a specific URL

In order to parse JSON, I want to load the text from a specific website. My code works on many websites such as http://api.openweathermap.org or http://stackoverflow.com. The code loads the json text or the sourcecode of any non-json url. However the code returns an empty String if I try to load the text from this specific url: https://www.instagram.com/1x/?__a=1. I have no Idea why it won´t work.

public String getJsonStringFromUrl(String url) {

    // make HTTP request
    try {

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();

    } catch (Exception e) {
        Log.e(TAG, "Error converting result " + e.toString());
    }

    return json;
}

Upvotes: 0

Views: 41

Answers (1)

Aljosha
Aljosha

Reputation: 222

As @DSlomer64 mentioned, the problem was the deprecated DefaultHttpClient. It works fine with okhttp

import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class GetTextFromUrl {
    OkHttpClient client = new OkHttpClient();

    String run(String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .build();

        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }

}

Upvotes: 1

Related Questions