android InputStream 无法从服务器页面获取输入
android InputStream cannot get inout from server page
您好,我正在使用以下代码,但无法从 url
获取 iStream
。 url returns 一个 JSON 数组。
URL url = new URL(tomato_search);
URLConnection urlConnection = url.openConnection();
InputStream iStream = new BufferedInputStream(urlConnection.getInputStream());
readStream(iStream);
iStream.close();
如果您使用 http 进行通信,最好使用 HttpURLConnection。
JsonArray jsonArray;
HttpURLConnection httpURLConnection = (HttpURLConnection) new URL("http://www.example.com/endpoint").openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
httpURLConnection.connect();
InputStream is = httpsURLConnection.getInputStream();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuilder sb = new StringBuilder();
while (br.readLine() != null) {
sb.append(br.readLine()).append("\n");
}
br.close();
jsonArray = new JSONArray(sb.toString());
} catch (IOException | JSONException e) {
jsonArray = null;
}
您好,我正在使用以下代码,但无法从 url
获取 iStream
。 url returns 一个 JSON 数组。
URL url = new URL(tomato_search);
URLConnection urlConnection = url.openConnection();
InputStream iStream = new BufferedInputStream(urlConnection.getInputStream());
readStream(iStream);
iStream.close();
如果您使用 http 进行通信,最好使用 HttpURLConnection。
JsonArray jsonArray;
HttpURLConnection httpURLConnection = (HttpURLConnection) new URL("http://www.example.com/endpoint").openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
httpURLConnection.connect();
InputStream is = httpsURLConnection.getInputStream();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuilder sb = new StringBuilder();
while (br.readLine() != null) {
sb.append(br.readLine()).append("\n");
}
br.close();
jsonArray = new JSONArray(sb.toString());
} catch (IOException | JSONException e) {
jsonArray = null;
}