How to Use Both HTTPS and HTTP to parse JSON data

2020-06-28 01:44发布

问题:

I followed this to Parse Json In Android

I have Successfully Done it with HttpData handler..

Here I am Successfully Posting Data to server and Getting Response..

Now I want to Use this same in the Part of HTTPS..

Can Any one suggest me How to do this Without Major Changes in my code.. Because In my application I am doing this for more activities.. Please Suggest me to Use HTTPs in my code..

I will provide Additional Info... Depending Responses...

Update In my code I have Changed HttpURLConnection to HttpsURLConnection

Please suggest me How to through this error In my code..

Update 1

I have Changed Certificate on server side.. Now its working On Https..

But Now,

I want to Use HTTP and HTTPS Both in one app Depending on Client Requirement So here now its worked with Https....

But I also need to work with Http In my Code Can any any one suggest me...I want I should Work with Https and Http Both In one App.

回答1:

to use both HTTP and HTTPS, you need to have the 2 methods (i think you already have them)

  1. GetHTTPData(String urlString)
  2. GetHTTPSData(String urlString)

now in HTTPDataHandler class (where you have both methods above) you need to create a 3rd method GetDataFromUrl(), that will check URL and decide which method to use (http or https)

public String GetDataFromUrl(String url){
    if(url.toLowerCase().startsWith("https")){
        //HTTPS:
        return GetHTTPSData(url);
    }else{
        //HTTP:
        return GetHTTPData(url);
    }
}

now in the AsyncTask class ProcessJSON

replace this line stream = hh.GetHTTPData(urlString);

with this one stream = hh.GetDataFromUrl(urlString);

if you don't want to add that 3rd method in HTTPDataHandler, just use the if-statement in ProcessJSON at doInBackground() to call either one of the 2 methods (http or https)



回答2:

You can use HttpsURLConnection, replace HttpURLConnection by HttpsURLConnection .

   public String GetHTTPData(String urlString){
        try{
            URL url = new URL(urlString);
            HttpsURLConnection urlConnection =(HttpsURLConnection)url.openConnection();

            // Check the connection status
            if(urlConnection.getResponseCode() == 200)
            {
                // if response code = 200 ok
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());

                // Read the BufferedInputStream
                BufferedReader r = new BufferedReader(new InputStreamReader(in));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = r.readLine()) != null) {
                    sb.append(line);
                }
                stream = sb.toString();
                // End reading...............

                // Disconnect the HttpURLConnection
                urlConnection.disconnect();
            }
            else
            {
                // Do something
            }
        }catch (MalformedURLException e){
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }finally {

        }
        // Return the data from specified url
        return stream;
    }


回答3:

What I understand is in your server side, they used self signed SSL certificate. So you have to install that certificate in your android device also. Settings > Security > install form storage.But for production build you have to buy ssl certificate from CA Authorities. Hope this will solve your problem.



回答4:

Remove HttpDataHandler lines in doInBackground use HttpUrlConnection directly in doInBackground or use HttpUrlConnection in JSONparse class to post params to server follow this tutorial to post params Website



回答5:

I have same issue so i have uses this code

// always verify the host - dont check for certificate
 final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier()
 {
    public boolean verify(String hostname, SSLSession session)
    {
        return true;
    }
 };

 /**
  * Trust every server - dont check for any certificate
  */
 @SuppressLint("TrulyRandom")
 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();
    }
 }

Updated code as per your requirement.

 public String postData(String urlString) throws JSONException, IOException
 {
     String result = "";
     try
        {

        HttpURLConnection http = null;
        URL url = new URL(urlString);

        if (url.getProtocol().toLowerCase().equals("https"))
        {
            trustAllHosts();
            HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
            https.setHostnameVerifier(DO_NOT_VERIFY);
            http = https;
        }
        else {
            http = (HttpURLConnection) url.openConnection();
        }
        Log.i("getDate", "="+http.getDate());
        http.connect();
        result = convertStreamToString((InputStream)http.getContent());
        Log.i("tag", "="+result);
        return result;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
static String convertStreamToString(java.io.InputStream is)
{
    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}

replace this line stream = hh.GetHTTPData(urlString);

with this one stream = postData(urlString);