3

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.

Don't Be negative
  • 1,129
  • 3
  • 17
  • 44
  • Https is different from http as it is safe and uses SSL – Nitesh Mar 19 '16 at 05:49
  • Recently My Server Changed to Https... So I want to Use Https in my activity... I am new to JSON please Suggest me On my Activity to Use Https without any major Changes... If Possible Give me a Example... I my Url if I give I am getting error.. for SSL... Because I am using http data handler.. suggest me for Https.. With that example code – Don't Be negative Mar 19 '16 at 05:53
  • Please read http://stackoverflow.com/questions/34293757/how-to-use-httpsurlconnection-instead-of-defaulthttpclient/34325483#34325483 to see if it can help or not – BNK Mar 19 '16 at 07:55
  • Thanks to all I Upvoted all of your answers – Don't Be negative Mar 31 '16 at 06:57

5 Answers5

3

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)

Yazan
  • 6,051
  • 1
  • 17
  • 32
1

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;
    }
  • Once Check my code http://android--examples.blogspot.in/2015/05/how-to-parse-json-data-in-android.html and update your answer in it – Don't Be negative Mar 19 '16 at 06:41
  • Sir I am getting This error "**javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.**" But I type same URL on pc Firefox is broswer I got this "Your connection is not secure" after Allowing.. in advance I got result.. But what should I need to do know **Your Answer is working I think but not getting any response from server** Plese help me sir... – Don't Be negative Mar 19 '16 at 07:10
  • checkout this url, may you get some help http://developer.android.com/training/articles/security-ssl.html#CommonProblems – Shripad Jadhav Mar 19 '16 at 07:15
  • thanks @Shripad Jadhav ,, Now please check my updated Questions – Don't Be negative Mar 22 '16 at 07:13
1

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.

Ankur Samarya
  • 207
  • 1
  • 3
  • 13
1

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

MPG
  • 785
  • 6
  • 20
  • Sir Can you suggest me how to use this in my code... In the part of Http and Https I have done with certificate etc... now its working with either Http by this http://android--examples.blogspot.in/2015/05/how-to-parse-json-data-in-android.html or https by this http://stackoverflow.com/a/36098429/5010291 Can you suggest me to use both In my code,,, – Don't Be negative Mar 22 '16 at 09:46
  • use above code, it will work with http or https. If any problem in my code let me know. thanks – MPG Mar 22 '16 at 09:58
  • in my code i am using POST method if you require GET method you can modify as per your requirement . – MPG Mar 22 '16 at 10:00
  • Thanks @MPG Can you Update your answer in my code... Check here http://android--examples.blogspot.in/2015/05/how-to-parse-json-data-in-android.html Please Update Your Answer I will Give Bounty.. I am new to Web services... – Don't Be negative Mar 24 '16 at 03:47
1

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

pavan kvch
  • 129
  • 1
  • 13