2012-04-01 142 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