2012-04-01 119 views
14

我想送一個HTTPS GET請求到谷歌購物API但是沒有什麼很爲我工作,例如這裏就是我想要的那一刻:的Android - 發送HTTPS Get請求

try {   
     HttpClient client = new DefaultHttpClient(); 
     HttpGet request = new HttpGet(); 
     request.setURI(new URI("https://www.googleapis.com/shopping/search/v1/public/products/?key={my_key}&country=&q=t-shirts&alt=json&rankByrelevancy=")); 
     HttpResponse response = client.execute(request); 
    } catch (URISyntaxException e) { 
     e.printStackTrace(); 
    } catch (ClientProtocolException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    return response; 
}  

如果任何人有任何建議,如何改善或取代它請讓我知道,在此先感謝。

+1

那不是完整的代碼在'response'變量上面的場景是不是在return語句的範圍。即你在你的try塊中聲明它,這樣就不會工作。發生什麼事了? – Blundell 2012-04-01 20:44:46

+0

我編輯了我的帖子以包含try支架,但就是這樣。我應該刪除try和catch括號,並使用'throws exception ...',這樣我可以訪問響應變量? – 2012-04-01 21:24:22

+2

什麼不行?任何異常,Logcat?當問題來自httpClient時,我建議的第一件事情是檢查響應狀態碼,例如httpResponse.getStatusLine()。getStatusCode(); – yorkw 2012-04-01 21:26:26

回答

38

你應該會收到一個編譯錯誤。

這是正確的版本:

HttpResponse response = null; 
try {   
     HttpClient client = new DefaultHttpClient(); 
     HttpGet request = new HttpGet(); 
     request.setURI(new URI("https://www.googleapis.com/shopping/search/v1/public/products/?key={my_key}&country=&q=t-shirts&alt=json&rankByrelevancy=")); 
     response = client.execute(request); 
    } catch (URISyntaxException e) { 
     e.printStackTrace(); 
    } catch (ClientProtocolException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    return response; 
} 

因此,如果現在你有你的迴應將返回爲空的錯誤。

一旦你有了迴應,並且檢查它爲空,你就會想要得到內容(即你的JSON)。

http://developer.android.com/reference/org/apache/http/HttpResponse.html http://developer.android.com/reference/org/apache/http/HttpEntity.html http://developer.android.com/reference/java/io/InputStream.html

response.getEntity().getContent(); 

這給你一個InputStream一起工作。如果你想將其轉換爲一個字符串,你會做以下或等價的:

http://www.mkyong.com/java/how-to-convert-inputstream-to-string-in-java/

public static String convertStreamToString(InputStream inputStream) throws IOException { 
     if (inputStream != null) { 
      Writer writer = new StringWriter(); 

      char[] buffer = new char[1024]; 
      try { 
       Reader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"),1024); 
       int n; 
       while ((n = reader.read(buffer)) != -1) { 
        writer.write(buffer, 0, n); 
       } 
      } finally { 
       inputStream.close(); 
      } 
      return writer.toString(); 
     } else { 
      return ""; 
     } 
    } 

當你有這樣的字符串,你需要從它創建一個JSONObject:

http://developer.android.com/reference/org/json/JSONObject.html

JSONObject json = new JSONObject(inputStreamAsString); 

完成!

+0

完美無瑕地工作,不能夠感謝你! – 2012-04-02 16:31:19

+0

不適合我嗎? SSLPeerUnspicifiedException發生:( – 2017-04-21 10:51:39

6

你添加到您的清單

<uses-permission android:name="android.permission.INTERNET" /> 
+0

是的,謝謝。 – 2012-04-01 21:21:49

0

很難肯定地說,如果你不告訴我們是什麼錯誤。

但是,如果您在UI線程上運行此操作,並且Web服務器需要超過幾秒的響應時間,則系統會收到「應用程序無響應」警告。確保您在單獨的線程上進行任何網絡傳輸。

3

,您可以嘗試這種方式也許使用URLConnection類

String error = ""; // string field 
private String getDataFromUrl(String demoIdUrl) { 

    String result = null; 
    int resCode; 
    InputStream in; 
    try { 
     URL url = new URL(demoIdUrl); 
     URLConnection urlConn = url.openConnection(); 

     HttpsURLConnection httpsConn = (HttpsURLConnection) urlConn; 
     httpsConn.setAllowUserInteraction(false); 
     httpsConn.setInstanceFollowRedirects(true); 
     httpsConn.setRequestMethod("GET"); 
     httpsConn.connect(); 
     resCode = httpsConn.getResponseCode(); 

     if (resCode == HttpURLConnection.HTTP_OK) { 
      in = httpsConn.getInputStream(); 

      BufferedReader reader = new BufferedReader(new InputStreamReader(
        in, "iso-8859-1"), 8); 
      StringBuilder sb = new StringBuilder(); 
      String line; 
      while ((line = reader.readLine()) != null) { 
       sb.append(line).append("\n"); 
      } 
      in.close(); 
      result = sb.toString(); 
     } else { 
      error += resCode; 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    return result; 
} 
+0

java.lang.ClassCastException:com.android.okhttp.internal.http.HttpURLConnectionImpl無法轉換爲javax.net.ssl.HttpsURLConnection – beetree 2016-09-20 23:17:39

+0

哦哇,失敗。我試圖請求一個「http」url。很好...... – beetree 2016-09-20 23:49:13

+0

如果我在這段代碼中使用'HttpURLConnection'而不是'HttpsURLConnection',會有什麼區別?因爲'HttpsURLConnection'從'HttpURLConnection'繼承,所以同一個實例的相同方法將會在''上被調用。連接'和'.getInputStream'。我錯了嗎? – 2017-01-23 01:46:06