【问题标题】:Make an request to HTTPS server by hitting a servlet通过点击 servlet 向 HTTPS 服务器发出请求
【发布时间】:2023-03-20 04:48:01
【问题描述】:

这是我在 http 服务器上向 servlet 发出 post 请求的代码

private static void post(String endpoint, Map<String, String> params)
        throws IOException {
    URL url;
    try {
        url = new URL(endpoint);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + endpoint);
    }
    StringBuilder bodyBuilder = new StringBuilder();
    Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
    // constructs the POST body using the parameters
    while (iterator.hasNext()) {
        Entry<String, String> param = iterator.next();
        bodyBuilder.append(param.getKey()).append('=')
                .append(param.getValue());
        if (iterator.hasNext()) {
            bodyBuilder.append('&');
        }
    }
    String body = bodyBuilder.toString();
    Log.v(TAG, "Posting '" + body + "' to " + url);
    byte[] bytes = body.getBytes();
    HttpURLConnection conn = null;


    try {
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setFixedLengthStreamingMode(bytes.length);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded;charset=UTF-8");
        // post the request
        OutputStream out = conn.getOutputStream();
        out.write(bytes);
        out.close();
        // handle the response
        int status = conn.getResponseCode();
        if (status != 200) {
          throw new IOException("Post failed with error code " + status);
        }
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
  }

当我的端点类似于 http://myipaddress:myport/ 时,它运行良好,但是当我将其更改为 https 连接不工作我也读过HttpsURLConnection,但我不知道如何在那里实现它,他们已经写了这段代码:

KeyStore keyStore = ...;
   TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
   tmf.init(keyStore);

   SSLContext context = SSLContext.getInstance("TLS");
   context.init(null, tmf.getTrustManagers(), null);

   URL url = new URL("https://www.example.com/");
   HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
   urlConnection.setSSLSocketFactory(context.getSocketFactory());
   InputStream in = urlConnection.getInputStream();

但我无法获得 Keystore 中应该包含的内容,我只有文件文件,如果我使用 Keystore.getInstance(String type) 如何获得证书类型。

请帮帮我。

【问题讨论】:

    标签: android servlets


    【解决方案1】:

    请检查此项以向安全服务器发出发布请求

    //请求

        String Verify_Mobile_URL ="https://www.sample.php";
                            try 
                            {
    
                                StringBuilder postDataBuilder = new StringBuilder();
                                postDataBuilder.append("param1").append("=").append("paramvalue");
                                postDataBuilder.append("&").append("param2").append("=").append("paramvalue");
    
    
                                byte[] postData = postDataBuilder.toString().getBytes();
    
                                // Hit the dm URL.
    
                                URL url = new URL(Verify_Mobile_URL);
                                HttpsURLConnection.setDefaultHostnameVerifier(new AllVerifier());
                                SSLContext sslContext = SSLContext.getInstance("TLS");
                                sslContext.init(null, new TrustManager[] { new AllTrustManager() }, null);
                                HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
                                HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();        
                                conn.setReadTimeout(60000);
                                conn.setConnectTimeout(35000);
                                conn.setDoOutput(true);
                                conn.setUseCaches(false);
                                conn.setRequestMethod("POST");
                                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                                conn.setRequestProperty("Content-Length",Integer.toString(postData.length));
    
                                OutputStream out = conn.getOutputStream();
                                out.write(postData);
                                out.close();
    
                                int responseCode = conn.getResponseCode();
                                if(responseCode==200)
                                {
                                    InputStream inputstream=conn.getInputStream();  
                                    String result=streamToString(inputstream);   // here you will will get result from
    
                                }
                                catch(Exception e)
                                {
                                }
    
    
    
    
    
    
    
    /**
         * This method convert inputstream to string
         * @param is - inputtream to be converted
         * @return String - converted string 
         */
        public static String streamToString(InputStream is)
        {
            DataInputStream din = new DataInputStream(is);
            StringBuffer sb = new StringBuffer();
            try {
                String line = null;
                while ((line = din.readLine()) != null) 
                {
                    sb.append(line + "\n");
                }
    
            } 
            catch (Exception ex) 
            {}      
    
            finally 
            {
                try 
                {  if(is!=null)
                    {
                        din.close();
                        is.close();
                    }
                } 
                catch (Exception ex) 
                {}
    
            }
            return sb.toString();
    
        }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    public class AllTrustManager implements X509TrustManager {
    
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
            // TODO Auto-generated method stub
    
        }
    
        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
            // TODO Auto-generated method stub
    
        }
    
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            // TODO Auto-generated method stub
            return new X509Certificate[0];
        }
    
    }
    
    
    
    
    
    public class AllVerifier implements HostnameVerifier {
    
        @Override
        public boolean verify(String hostname, SSLSession session) {
            // TODO Auto-generated method stub
            return true;
        }
    
    }
    

    【讨论】:

    • 实际上我已经将它们定义为内部类,所以现在它给出了一个错误我所做的我已经通过直接使用新的 HostnameVerifier 和新的 X509TrustManager 覆盖了这些方法,并且它工作得很好,非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-04
    • 2012-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多