android - https 简单获取请求

标签 android ssl httpurlconnection

我正尝试按如下方式发出 get https 请求:

{
    URL url;
    String response = "";
    try {
        url = new URL(requestURL);

        HttpsURLConnection  connection = (HttspURLConnection) url.openConnection();

        connection.setRequestMethod("GET");
        connection.setDoOutput(true);
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);

        connection.connect();

        int responseCode =  connection.getResponseCode();
        if (responseCode == HttpsURLConnection.HTTP_OK) {
            String line;
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            while ((line = br.readLine()) != null) {
                response += line;
            }
            stringResponse = response;
        } else {


            stringResponse = "NONET";

            Log.e(Constants.tag, requestURL + " HTTP ERROR: "
                    + responseCode + "\n" +  connection.getResponseMessage());

        }
    } catch (UnknownHostException net) {


        Log.e(Constants.tag, requestURL + " HTTP ERROR", net);
        stringResponse = "NONET";

    } catch (SocketTimeoutException time) {


        Log.e(Constants.tag, requestURL + " HTTP ERROR", time);
        stringResponse = "NONET";

    } catch (SSLHandshakeException e) {


        Log.e(Constants.tag, requestURL + " HTTP ERROR", e);
        stringResponse = null;


    } catch (Exception e) {


        Log.e(Constants.tag, requestURL + " HTTP ERROR", e);
        stringResponse = null;


    } finally {

        received.set(true);


    }

    return response;
}

如果 URL 是 http 可以正常工作,但如果 url 是 https,我总是会收到以下错误。

E/NativeCrypto: ssl=0x7f80a06f80 cert_verify_callback x509_store_ctx=0x7f6afc02d8 arg=0x0 E/NativeCrypto: ssl=0x7f80a06f80 cert_verify_callback calling verifyCertificateChain authMethod=ECDHE_ECDSA
E/app tag: https://api(...)/all HTTP ERROR: 404 Not Found

我尝试从 Android 设备浏览器输入 https url,api 显示正确。 (是json api)

最佳答案

我已经为 HTTPS 服务器的所有 POST/PUT/GET 请求编写了一个函数

一个。您必须处理自签名证书的内容。请务必包括在内。

您必须指明要发送到服务器的内容类型。

取决于服务器配置。在处理 Android 请求之前,您发送到服务器的任何请求都通过 POSTMAN 或 curl 命令检查以验证是否正常工作。

这是我的示例代码。

 public String createConnection (String urlS, String methodInvoked,String patchBody, String postBody,String putBody){
            URL url ;
            BufferedReader br = null;
            String toBeReturned="";
            try {
                url = new URL(urlS);
                 HostnameVerifier hostnameVerifier = new HostnameVerifier() {
                    @Override

                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            };
            TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        public X509Certificate[] getAcceptedIssuers() {
                            X509Certificate[] myTrustedAnchors = new X509Certificate[0];
                            return myTrustedAnchors;
                        }
                        @Override
                        public void checkClientTrusted(X509Certificate[] certs, String authType) {
                        }
                        @Override
                        public void checkServerTrusted(X509Certificate[] certs, String authType) {
                        }
                    }
            };

            // Create an SSLContext that uses our TrustManager
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, null);


            HttpsURLConnection  connection = (HttpsURLConnection) url.openConnection();
            connection.setConnectTimeout(60000);
            HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
            connection.setSSLSocketFactory(sc.getSocketFactory());
            connection.setHostnameVerifier(hostnameVerifier);


            if (patchBody  != null ){
                Log.i(TAG, " createConnection with PATH with body" );
                connection.setRequestMethod("PATCH");
                connection.setRequestProperty("data",patchBody);
                connection.addRequestProperty("Content-Type", "application/json");
                DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());
                dStream.writeBytes(patchBody);
                dStream.flush();
                dStream.close();
            }
            if (methodInvoked.equalsIgnoreCase("PATCH") && patchBody == null ){
                Log.i(TAG, " createConnection with PATH without body" );
                connection.setRequestMethod("PATCH");
//              connection.addRequestProperty("Content-Type", "application/json");
//              connection.setDoOutput(true);
            }
            if (postBody != null){
                Log.i(TAG, " createConnection with POST with body" );
                connection.setRequestMethod("POST");
                connection.addRequestProperty("Content-Type", "application/json");
                connection.setDoOutput(true);
                DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());
                dStream.writeBytes(postBody);
                dStream.flush();
                dStream.close();
            }

            if (methodInvoked.equalsIgnoreCase("POST") && postBody == null ){
                Log.i(TAG, " createConnection with POST without body" );
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
                //connection.addRequestProperty("Content-Type", "application/json");
            }

            if (putBody != null){
                Log.i(TAG, " createConnection with PUT with body" );
                connection.setRequestMethod("PUT");
                connection.setDoOutput(true);
                connection.addRequestProperty("Content-Type", "application/json");
                DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());
                dStream.writeBytes(putBody);
                dStream.flush();
                dStream.close();
            }



            responseCode = connection.getResponseCode();
            InputStream in= null;
            if(responseCode >= HttpsURLConnection.HTTP_BAD_REQUEST)
            {   

                in = connection.getErrorStream();
                br = new BufferedReader( new InputStreamReader(connection.getErrorStream()));
                StringBuilder sb = new StringBuilder();
                String line = null; 
                while ((line = br.readLine()) != null) {
                    sb.append(line+"\n");
                }
                 String toBeReturned_1 = sb.toString();
                 Log.i(TAG, " createConnetion error received " +  responseCode  + "  " + toBeReturned_1) ;

            }
            else{


                br = new BufferedReader( new InputStreamReader(connection.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line = null; 
                while ((line = br.readLine()) != null) {
                    sb.append(line+"\n");
                }
                toBeReturned = sb.toString();


            }


        } catch (MalformedURLException e) {
            error = e.getMessage();
            e.printStackTrace();
        } catch (IOException e) {
            error = e.getMessage();
            e.printStackTrace();
        } catch (KeyManagementException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally{
            try {
                if (br!=null)
                    br.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
        Log.i(TAG, " createConnetion  finally returned" +  toBeReturned );
        return toBeReturned; 
    }

默认情况下,createconnection 函数将执行 GET 请求

对于 GET 请求,这样调用它:-

String urlS_ = "https://google.com"; // your URI
String methodInvoked = "GET"
createConnection (urlS_, methodInvoked,null, null,null)

对于 POST 请求,这样调用它:-

String urlS_ = "https://gmail.com"; // your URI
String methodInvoked = "POST"
String postBody = postbody_; // Create a postbody_ which  you want to create 
createConnection (urlS_, methodInvoked,null, postBody ,null)

你可以根据自己的需要裁剪函数

关于android - https 简单获取请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44116021/

相关文章:

Android 和带 SSL 的 HTTPS

Android:HttpURLConnection 不会断开连接

java - Android上的HttpURLConnection什么时候真正调用请求

android - 使用上游 Github Repo 使 Android Studio 保持最新

java - 如何通过蓝牙向 OBDII 适配器发送 ELM327 命令?

javascript - 使用 JavaScript 通过 https 提供图像

android - java.lang.OutOfMemoryError : Could not allocate JNI Env 错误

java - 尝试解析 JSON 数据时通过递归调用在 Android 中获取 StackOverFlowError

android - 使用 WindowManager 自定义布局

php - 无法连接到 ssl ://gateway. sandbox.push.apple.com:2195(连接被拒绝)