Android -urlConnection.getInputStream() 失败 - InputStream 保持为空
Android -urlConnection.getInputStream() fails - InputStream stays null
我正在尝试从 Android 中的 Google 方向服务器检索 JSON 数据。但是获取输入流失败并抛出异常。我收到错误消息 ,null" 并且输入流为空。
我在 HTTP 连接上做错了什么? URL 在我的浏览器上运行。
private String doRequest() {
String response = null;
HttpURLConnection urlConnection = null;
InputStream in = null;
URL url = null;
String queryString ="https://maps.googleapis.com/maps/api/directions/json?origin=40.71926430971954,-74.26603317260742&destination=40.74309523218185," +
"-74.24732208251953&sensor=false&mode=walking&alternatives=true&key=AIzaSyASF2b0E0HHilJL5I936vqRbiBjM5XuPRA";
try {
url = new URL(queryString);
urlConnection = (HttpURLConnection) url.openConnection();
in = urlConnection.getInputStream();
}
catch (Exception e) {
{
StringBuilder builder = new StringBuilder();
if (response == null)
builder.append("Response is null.");
if (url == null)
builder.append("url is null.");
if (urlConnection == null)
builder.append("UrlConnection is null.");
if (in == null)
builder.append("Inputstream is null.");
return builder.toString() +e.getMessage();
}
} finally {
if (urlConnection != null)
urlConnection.disconnect();
}
if (response == null)
{
return "sorry, response is null. At least it passed the exceptions.";
}
return response;
}
编辑:
Here is the error message
编辑 2:
好的,我已经尝试了所有建议的组合。现在,当我执行代码时,什么也没有发生。打不开对话框,不知道这次是什么问题
public void getJSON(View v)
{
AsyncTask<String, Void, String>hello = new GetData(this).execute(queryString);
}
导入android.app.Dialog;
进口android.app.ProgressDialog;
进口android.content.Context;
进口android.content.DialogInterface;
进口android.net.http.HttpsConnection;
进口android.os.AsyncTask;
导入android.support.v7.app.AlertDialog;
进口android.view.View;
进口java.io.InputStream;
导入java.net.HttpURLConnection;
进口java.net.URL;
进口javax.net.ssl.HttpsURLConnection;
(public class GetData 扩展 AsyncTask)
{
private Exception exception;
public String response;
private Context context;
private ProgressDialog dialog = null;
public GetData(Context context)
{
this.context = context;
}
protected String doInBackground(String... urls)
{
this.response = doRequest(urls[0]);
return response;
}
protected void onPostExecute() {
// TODO: check this.exception
// TODO: do something with the feed
if (this.exception != null && response != null)
{
getDialog(getResponse(), context).show();
}
else
{
getDialog("sorry" + exception.getMessage(), context).show();
}
}
private String doRequest(String queryString) {
String response1 = null;
HttpsURLConnection urlConnection = null;
InputStream in = null;
URL url = null;
try {
url = new URL(queryString);
urlConnection =(HttpsURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET"); // or POST
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
int responseCode = urlConnection.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK)
{
in = urlConnection.getInputStream();
response1 = convertStreamToString(in);
}
} catch (Exception e) {
{
StringBuilder builder = new StringBuilder();
if (response1 == null)
builder.append("Response is null.");
if (url == null)
builder.append("url is null.");
if (urlConnection == null)
builder.append("UrlConnection is null.");
if (in == null)
builder.append("Inputstream is null.");
return builder.toString() + e.getMessage();
}
}
finally
{
if (urlConnection != null)
urlConnection.disconnect();
}
if (response1 == null)
{
return "sorry, response is null. At least it passed the exceptions.";
}
return response1;
}
private String convertStreamToString(java.io.InputStream is)
{
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\A");
return s.hasNext() ? s.next() : "";
}
public String getResponse()
{
return this.response;
}
public Dialog getDialog(String string, Context context) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(string);
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return builder.create();
}
首先,将 Internet 权限添加到您的清单文件中:
<uses-permission android:name="android.permission.INTERNET" />
然后将此添加到您现有的代码中:
urlConnection.setRequestMethod("GET"); // or POST
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
然后检查响应代码:
if (responseCode == HttpURLConnection.HTTP_OK) {
}
您还应该将读取 InputStream 的方式更改为如下所示:
try {
BufferedReader input = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
StringBuilder strB = new StringBuilder();
String str;
while (null != (str = input.readLine())) {
strB.append(str).append("\r\n");
}
input.close();
} catch (IOException e) {
e.printStackTrace();
}
您的 link 使用 HTTPS 协议,但您试图将连接转换为 HTTP 而不是 HTTPS:
urlConnection = (HttpURLConnection) url.openConnection();
尝试删除转换并执行:
URLConnection urlConnection = url.openConnection();
或将其转换为 HTTPS:
urlConnection = (HttpsURLConnection) url.openConnection();
现在 InputStream 应该不为空。
此致
您可能会尝试在主线程的 doRequest() 中执行网络操作。 运行 你在 AsyncTask 中的代码 https://developer.android.com/reference/android/os/AsyncTask.html
以下代码可能对您有所帮助
问题出在您的 onPostExecute 和对话框上。你应该覆盖 onPostExecute 和 getDialog 将 return AlertDialog。每当您的请求成功时,异常都必须为空。检查我编辑的代码:
class GetData extends AsyncTask<String, Void, String> {
private Exception exception;
public String response;
private Context context;
private ProgressDialog dialog = null;
public GetData(Context context) {
this.context = context;
}
protected String doInBackground(String... urls) {
this.response = doRequest(urls[0]);
return response;
}
@Override
protected void onPostExecute(String s) {
// TODO: check this.exception
// TODO: do something with the feed
if (this.exception == null && response != null) {
getDialog(response, context).show();
} else {
getDialog("sorry" + exception.getMessage(), context).show();
}
}
private String doRequest(String queryString) {
HttpsURLConnection urlConnection = null;
InputStream in = null;
URL url = null;
try {
url = new URL(queryString);
urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET"); // or POST
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
int responseCode = urlConnection.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
in = urlConnection.getInputStream();
response = convertStreamToString(in);
}
} catch (Exception e) {
{
exception = e;
StringBuilder builder = new StringBuilder();
if (response == null)
builder.append("Response is null.");
if (url == null)
builder.append("url is null.");
if (urlConnection == null)
builder.append("UrlConnection is null.");
if (in == null)
builder.append("Inputstream is null.");
return builder.toString() + e.getMessage();
}
} finally {
if (urlConnection != null)
urlConnection.disconnect();
}
if (response == null) {
return "sorry, response is null. At least it passed the exceptions.";
}
return response;
}
private String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\A");
return s.hasNext() ? s.next() : "";
}
/* public String getResponse() {
return this.response;
}*/
public AlertDialog getDialog(String string, Context context) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(string);
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return builder.create();
}
}
public void getJSON(View v)
{
AsyncTask<String, Void, String>hello = new GetData(MainActivity.this).execute(queryString);//MainActivity will be your activity
}
我正在尝试从 Android 中的 Google 方向服务器检索 JSON 数据。但是获取输入流失败并抛出异常。我收到错误消息 ,null" 并且输入流为空。
我在 HTTP 连接上做错了什么? URL 在我的浏览器上运行。
private String doRequest() {
String response = null;
HttpURLConnection urlConnection = null;
InputStream in = null;
URL url = null;
String queryString ="https://maps.googleapis.com/maps/api/directions/json?origin=40.71926430971954,-74.26603317260742&destination=40.74309523218185," +
"-74.24732208251953&sensor=false&mode=walking&alternatives=true&key=AIzaSyASF2b0E0HHilJL5I936vqRbiBjM5XuPRA";
try {
url = new URL(queryString);
urlConnection = (HttpURLConnection) url.openConnection();
in = urlConnection.getInputStream();
}
catch (Exception e) {
{
StringBuilder builder = new StringBuilder();
if (response == null)
builder.append("Response is null.");
if (url == null)
builder.append("url is null.");
if (urlConnection == null)
builder.append("UrlConnection is null.");
if (in == null)
builder.append("Inputstream is null.");
return builder.toString() +e.getMessage();
}
} finally {
if (urlConnection != null)
urlConnection.disconnect();
}
if (response == null)
{
return "sorry, response is null. At least it passed the exceptions.";
}
return response;
}
编辑:
Here is the error message
编辑 2:
好的,我已经尝试了所有建议的组合。现在,当我执行代码时,什么也没有发生。打不开对话框,不知道这次是什么问题
public void getJSON(View v)
{
AsyncTask<String, Void, String>hello = new GetData(this).execute(queryString);
}
导入android.app.Dialog;
进口android.app.ProgressDialog;
进口android.content.Context;
进口android.content.DialogInterface;
进口android.net.http.HttpsConnection;
进口android.os.AsyncTask;
导入android.support.v7.app.AlertDialog;
进口android.view.View;
进口java.io.InputStream;
导入java.net.HttpURLConnection;
进口java.net.URL;
进口javax.net.ssl.HttpsURLConnection;
(public class GetData 扩展 AsyncTask)
{
private Exception exception;
public String response;
private Context context;
private ProgressDialog dialog = null;
public GetData(Context context)
{
this.context = context;
}
protected String doInBackground(String... urls)
{
this.response = doRequest(urls[0]);
return response;
}
protected void onPostExecute() {
// TODO: check this.exception
// TODO: do something with the feed
if (this.exception != null && response != null)
{
getDialog(getResponse(), context).show();
}
else
{
getDialog("sorry" + exception.getMessage(), context).show();
}
}
private String doRequest(String queryString) {
String response1 = null;
HttpsURLConnection urlConnection = null;
InputStream in = null;
URL url = null;
try {
url = new URL(queryString);
urlConnection =(HttpsURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET"); // or POST
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
int responseCode = urlConnection.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK)
{
in = urlConnection.getInputStream();
response1 = convertStreamToString(in);
}
} catch (Exception e) {
{
StringBuilder builder = new StringBuilder();
if (response1 == null)
builder.append("Response is null.");
if (url == null)
builder.append("url is null.");
if (urlConnection == null)
builder.append("UrlConnection is null.");
if (in == null)
builder.append("Inputstream is null.");
return builder.toString() + e.getMessage();
}
}
finally
{
if (urlConnection != null)
urlConnection.disconnect();
}
if (response1 == null)
{
return "sorry, response is null. At least it passed the exceptions.";
}
return response1;
}
private String convertStreamToString(java.io.InputStream is)
{
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\A");
return s.hasNext() ? s.next() : "";
}
public String getResponse()
{
return this.response;
}
public Dialog getDialog(String string, Context context) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(string);
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return builder.create();
}
首先,将 Internet 权限添加到您的清单文件中:
<uses-permission android:name="android.permission.INTERNET" />
然后将此添加到您现有的代码中:
urlConnection.setRequestMethod("GET"); // or POST
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
然后检查响应代码:
if (responseCode == HttpURLConnection.HTTP_OK) {
}
您还应该将读取 InputStream 的方式更改为如下所示:
try {
BufferedReader input = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
StringBuilder strB = new StringBuilder();
String str;
while (null != (str = input.readLine())) {
strB.append(str).append("\r\n");
}
input.close();
} catch (IOException e) {
e.printStackTrace();
}
您的 link 使用 HTTPS 协议,但您试图将连接转换为 HTTP 而不是 HTTPS:
urlConnection = (HttpURLConnection) url.openConnection();
尝试删除转换并执行:
URLConnection urlConnection = url.openConnection();
或将其转换为 HTTPS:
urlConnection = (HttpsURLConnection) url.openConnection();
现在 InputStream 应该不为空。
此致
您可能会尝试在主线程的 doRequest() 中执行网络操作。 运行 你在 AsyncTask 中的代码 https://developer.android.com/reference/android/os/AsyncTask.html 以下代码可能对您有所帮助
问题出在您的 onPostExecute 和对话框上。你应该覆盖 onPostExecute 和 getDialog 将 return AlertDialog。每当您的请求成功时,异常都必须为空。检查我编辑的代码:
class GetData extends AsyncTask<String, Void, String> {
private Exception exception;
public String response;
private Context context;
private ProgressDialog dialog = null;
public GetData(Context context) {
this.context = context;
}
protected String doInBackground(String... urls) {
this.response = doRequest(urls[0]);
return response;
}
@Override
protected void onPostExecute(String s) {
// TODO: check this.exception
// TODO: do something with the feed
if (this.exception == null && response != null) {
getDialog(response, context).show();
} else {
getDialog("sorry" + exception.getMessage(), context).show();
}
}
private String doRequest(String queryString) {
HttpsURLConnection urlConnection = null;
InputStream in = null;
URL url = null;
try {
url = new URL(queryString);
urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET"); // or POST
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
int responseCode = urlConnection.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
in = urlConnection.getInputStream();
response = convertStreamToString(in);
}
} catch (Exception e) {
{
exception = e;
StringBuilder builder = new StringBuilder();
if (response == null)
builder.append("Response is null.");
if (url == null)
builder.append("url is null.");
if (urlConnection == null)
builder.append("UrlConnection is null.");
if (in == null)
builder.append("Inputstream is null.");
return builder.toString() + e.getMessage();
}
} finally {
if (urlConnection != null)
urlConnection.disconnect();
}
if (response == null) {
return "sorry, response is null. At least it passed the exceptions.";
}
return response;
}
private String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\A");
return s.hasNext() ? s.next() : "";
}
/* public String getResponse() {
return this.response;
}*/
public AlertDialog getDialog(String string, Context context) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(string);
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return builder.create();
}
}
public void getJSON(View v)
{
AsyncTask<String, Void, String>hello = new GetData(MainActivity.this).execute(queryString);//MainActivity will be your activity
}