Android - 发送HTTPS获取请求

时间:2012-04-01 20:38:14

标签: android http https get httpclient

我想向Google购物API发送一个HTTPS获取请求,但是没有什么对我有用,例如,这是我正在尝试的内容:

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;
}    

如果有人对如何改进或更换它有任何建议,请提前告知我们。

6 个答案:

答案 0 :(得分:40)

您应该收到编译错误。

这是正确的版本:

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;
}

因此,现在如果您有错误,您的回复将返回为null。

获得响应并将其检查为null后,您将要获取内容(即您的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);

完成!

答案 1 :(得分:6)

您是否已将此添加到清单

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

答案 2 :(得分: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;
}

答案 3 :(得分:2)

  

我在这里写了两个方法。复制它们。在你的第一个方法中,uri =你要发送请求的网址:

     

第一种方法:

public  static String Getdata (String uri ){

        BufferedReader reader = null;

        try {

            URL url = new URL(uri);
            HttpURLConnection con = null;

            URL testUrlHttps = new URL(uri);
            if (testUrlHttps.getProtocol().toLowerCase().equals("https"))
            {
                trustAllHosts();
                HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
                https.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
                con = https;
            } else
            {
                con = (HttpURLConnection) url.openConnection();
            }


            con.setReadTimeout(15000);
            con.setConnectTimeout(15000);
            StringBuilder sb = new StringBuilder();
            reader = new BufferedReader(new InputStreamReader(con.getInputStream()));

            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            return sb.toString();

        } catch (Exception e) {
            e.printStackTrace();
            return "";
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    return "";
                }
            }
        }
    }
  

另一种完全信任第一种方法认证的方法。

     

第二种方法:

private static void trustAllHosts()
    {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager()
        {
            public java.security.cert.X509Certificate[] getAcceptedIssuers()
            {
                return new java.security.cert.X509Certificate[] {};
            }

            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException
            {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException
            {
            }
        } };

        // Install the all-trusting trust manager
        try
        {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }

答案 4 :(得分:1)

感谢Make HTTPS / HTTP Request in Android

添加Java类 CustomSSLSocketFactory.java

 import java.io.IOException;
 import java.net.Socket;
 import java.net.UnknownHostException;
 import java.security.KeyManagementException;
 import java.security.KeyStore;
 import java.security.KeyStoreException;
 import java.security.NoSuchAlgorithmException;
 import java.security.UnrecoverableKeyException;
 import java.security.cert.CertificateException;
 import java.security.cert.X509Certificate;
 import javax.net.ssl.SSLContext;
 import javax.net.ssl.TrustManager;
 import javax.net.ssl.X509TrustManager;
 import org.apache.http.conn.ssl.SSLSocketFactory;

 public class CustomSSLSocketFactory extends SSLSocketFactory{
SSLContext sslContext = SSLContext.getInstance("TLS");
/**
 * Generate Certificate for ssl connection
 * @param truststore
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 * @throws KeyStoreException
 * @throws UnrecoverableKeyException
 */
public CustomSSLSocketFactory(KeyStore truststore)
        throws NoSuchAlgorithmException, KeyManagementException,
        KeyStoreException, UnrecoverableKeyException {
    super(truststore);
    TrustManager tm = new X509TrustManager(){
        @Override
        public void checkClientTrusted(X509Certificate[] arg0, String arg1)
                throws CertificateException {
        }
        @Override
        public void checkServerTrusted(X509Certificate[] chain,
                                       String authType) throws CertificateException {
        }
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };
    sslContext.init(null, new TrustManager[] {tm}, null);
}

@Override
public Socket createSocket(Socket socket, String host, int port,
                           boolean autoClose) throws IOException, UnknownHostException {
    return sslContext.getSocketFactory().createSocket(socket, host, port,
            autoClose);
}

@Override
public Socket createSocket() throws IOException {
    return sslContext.getSocketFactory().createSocket();
}
 }

在您的代码中

    String cloud_url="https://www.google.com";
    HttpClient client = new DefaultHttpClient();
        if(cloud_url.toLowerCase().contains("https://")){
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);
            SSLSocketFactory sf = new CustomSSLSocketFactory(trustStore);
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

            HttpParams params = new BasicHttpParams();
            SchemeRegistry registry = new SchemeRegistry();
            registry.register(new Scheme("https", sf, 443));

            ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
            client= new DefaultHttpClient(ccm, params);
        }


        HttpGet request= new HttpGet( );
        request.setURI(new URI( cloud_url));
        HttpResponse response = client.execute(request);

在HttpPost中也可以使用。

答案 5 :(得分:0)

如果你不告诉我们错误是什么,很难肯定。

但是如果你在UI线程上运行它并且Web服务器需要几秒钟的时间来响应,你将从系统获得一个Application Not Responding警告。确保在单独的线程上进行任何网络传输。