为了解析JSON,我想从特定网站加载文本。 我的代码适用于许多网站,例如http://api.openweathermap.org或http://stackoverflow.com。代码加载任何非json url的json文本或源代码。但是,如果我尝试从此特定URL加载文本,则代码将返回一个空字符串:https://www.instagram.com/1x/?__a=1。 我不知道为什么它不起作用。
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;
}
答案 0 :(得分:1)
提到@DSlomer64时,问题是已弃用的 DefaultHttpClient 。 它适用于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();
}
}
}