2017-04-03 25 views
0

我試圖從Android中的Google Directions服務器檢索JSON數據。但是獲取輸入流失敗並拋出異常。我收到錯誤消息,,空」,而InputStream爲空Android -urlConnection.getInputStream()失敗 - InputStream保留爲空

我在做什麼錯誤的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; 
} 

EDIT?:

Here is the error message


編輯2:

好吧,我已經嘗試了各種建議的組合。現在當我執行代碼時,什麼都沒有發生。我無法打開對話框,所以我不知道這次是什麼問題。

public void getJSON(View v) 
{ 
    AsyncTask<String, Void, String>hello = new GetData(this).execute(queryString); 
} 

import android.app.Dialog;

import android.app.ProgressDialog;

import android.content.Context;

import android.content.DialogInterface;

import android.net.http.HttpsConnection;

import android.os.AsyncTask;

import android.support.v7.app.AlertDialog;

import android.view.View;

import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.URL;

import javax.net.ssl。HttpsURLConnection的;

(公共類的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(); 

} 
+0

檢查互聯網連接 –

+0

請張貼您的導入包爲HttpURLConnection。 –

+0

e.getMessage()包含什麼? – greenapps

回答

0

您可能會嘗試在主線程的doRequest()中執行聯網操作。在AsyncTask中運行代碼https://developer.android.com/reference/android/os/AsyncTask.html 以下代碼可能會對您有所幫助

問題出在您的onPostExecute和對話框上。你應該重寫onPostExecute並且getDialog將返回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 
} 
+0

這是真的,我試圖執行MainActivity中的代碼。不過,我已經嘗試過使用AsyncTask,但它仍然無法正常工作。我究竟做錯了什麼? –

+0

@Karl Ball現在你面臨的問題是什麼。上面的代碼對我很好。 – user7676575

+0

@Karl Ball問題出現在onPostExecute和對話框中。你應該重寫onPostExecute並且getDialog將返回AlertDialog。每當您的請求成功時,異常必須爲空。檢查我編輯的代碼。 – user7676575

0

首先,添加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(); 
} 
+0

我試過了,但沒有任何反應。 –

0

使用您的鏈接HTTPS協議,但你要投連接到HTTP不是HTTPS:

urlConnection = (HttpURLConnection) url.openConnection(); 

嘗試刪除鑄造,做:

URLConnection urlConnection = url.openConnection(); 

或者將其轉換爲HTTPS:

urlConnection = (HttpsURLConnection) url.openConnection(); 

現在的InputStream應不空。

Regards