-1

WHAT I NEED: get JSON results through HTTPS connection

WHAT I HAVE: shared server with valid SSL certificate

WHAT I WANT: be able to establish that HTTPS connection, which I can't because when I chaneg my code with the online examples I found, it never works...

DETAILS:

I have been searching for days a solution, but I find many different things and already tried a lot of different combinations in my code and nothing worked. :(

I'm used to develop in PHP, MySQL, CSS, HTML but only recently I started with Android (java) and I had never developed anything at all (not even a "Hello world!").

I wanted a simple APP and I hired someone in freelancer (excelent Indian guy, actually... I consider myself lucky on this one).

So, I recently bought an SSL/TLS certificate for my website, which is on a shared server, and I want to change my code on my APP to be able to connect through HTTPS and make that a safe connection to the webservice I have developed in PHP.

Everything is working perfectly with HTTP requests but when I try some different HTTPS recommendations that I found online, nothing worked. :(

Could never reach a conclusion about this. lol

Here is my code of one in some 30 different screens:

    package com.appname.othername;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import com.actionbarsherlock.app.SherlockFragment;
import com.andreabaccega.widget.FormEditText;
import com.appname.R;
import com.appname.R.id;
import com.appname.R.layout;
import com.appname.Visiter.NewJobRequestFragment.SenderTask;
import com.appname.utility.ConnectionDetector;
import com.appname.utility.JsonHandler;
import com.appname.utility.ServiceHandler;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

public class CallmeFragment extends SherlockFragment {

    public static final String serverURL = "http://WEBSITE.COM/WEBSERVICE_FILE.PHP";
    public static final String TAG_RESULT = "result";
    public static final String TAG_ERROR_STATUS = "error";
    public static final String TAG_ERROR_MSG = "message";
    private FormEditText firstname;
    private FormEditText email;
    private FormEditText phone;

    private ProgressDialog progressDialog;
    private ArrayList<NameValuePair> nameValuePair;
    public String httpresponce;
    public JSONObject result;
    public String error_status;
    public String error_msg;
    private boolean isInternetPresent;
    private ConnectionDetector cd;

    public CallmeFragment(){}

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
         progressDialog = new ProgressDialog(getActivity());
         progressDialog.setMessage("Please wait...");
         progressDialog.setCancelable(false);

         cd = new ConnectionDetector(getActivity());
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_callme, container, false);
         firstname = (FormEditText)rootView.findViewById(R.id.editText1);
         email = (FormEditText)rootView.findViewById(R.id.editText2);
         phone = (FormEditText)rootView.findViewById(R.id.editText3);
         phone.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {
                final int length = phone.getText().length();
                 phone.setOnKeyListener(new OnKeyListener() {
                        @Override
                        public boolean onKey(View v, int keyCode, KeyEvent event) {

                            if (length  ==3 || length ==7 && keyCode != KeyEvent.KEYCODE_DEL)
                            {
                                 phone.setText(phone.getText() + " ");
                                phone.setSelection(phone.getText().length());
                            }
                            return false;
                        }
                    });
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

            }

         });
         Button submit_button = (Button)rootView.findViewById(R.id.button1);
         submit_button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                ValidateForms();
                // TODO Auto-generated method stub

            }
        });
        return rootView;
    }

    protected void ValidateForms() {
        // TODO Auto-generated method stub
        FormEditText[] allFields    = {firstname,email,phone};


        boolean allValid = true;
        for (FormEditText field: allFields) {
            allValid = field.testValidity() && allValid;
        }

        if (allValid) {
          SendMail();
        } else {
            // EditText are going to appear with an exclamation mark and an explicative message.
        }
    }

    private void SendMail() {
         nameValuePair = new ArrayList<NameValuePair>(8);
           nameValuePair.add(new BasicNameValuePair("name",firstname.getText().toString()));
           nameValuePair.add(new BasicNameValuePair("contact",phone.getText().toString()));
           nameValuePair.add(new BasicNameValuePair("email",email.getText().toString()));
           isInternetPresent = cd.isConnectingToInternet();
           if (isInternetPresent) {
                   new SenderTask().execute();
           }
           else
           {
               Toast.makeText(getActivity(),"Internet connection failed", Toast.LENGTH_SHORT).show();
           }
    }
    class SenderTask extends AsyncTask<String, Void, Void> {

        @Override
        protected void onPreExecute() {
            progressDialog.show();
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(String... params) {
    ServiceHandler sh = new ServiceHandler();

            // Making a request to url and getting response
              httpresponce = sh.makeServiceCall(serverURL , JsonHandler.POST,nameValuePair);
              if (httpresponce != null) {
                    try {
                        JSONObject jsonObj = new JSONObject(httpresponce);

                        // Getting JSON Array node
                        result = jsonObj.getJSONObject(TAG_RESULT);
                          error_status  = result.getString(TAG_ERROR_STATUS);
                         error_msg = result.getString(TAG_ERROR_MSG);

                    } catch (JSONException e) {
                        e.printStackTrace();

                    }

                    }
            Log.i("Responce", "= "+httpresponce);
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            progressDialog.dismiss();
            showAlert();
            super.onPostExecute(result);
        }
    }
    public void showAlert() {
        // TODO Auto-generated method stub
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                getActivity());

            // set title
            alertDialogBuilder.setTitle("Message");

            // set dialog message
            alertDialogBuilder
                .setMessage(error_msg)
                .setCancelable(true)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
                //do things
           }
       });  // create alert dialog
                AlertDialog alertDialog = alertDialogBuilder.create();

                // show it
                alertDialog.show();
    }

}

EDIT:

Here is the error after giving some tries chenging things:

10-05 22:40:21.673: W/System.err(10007): javax.net.ssl.SSLException: hostname in certificate didn't match: <maif.pt> != <www.infor5.pt> OR <www.infor5.pt> OR <infor5.pt>
10-05 22:40:21.673: W/System.err(10007):    at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:185)
10-05 22:40:21.673: W/System.err(10007):    at org.apache.http.conn.ssl.BrowserCompatHostnameVerifier.verify(BrowserCompatHostnameVerifier.java:54)
10-05 22:40:21.673: W/System.err(10007):    at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:114)
10-05 22:40:21.673: W/System.err(10007):    at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:95)
10-05 22:40:21.673: W/System.err(10007):    at org.apache.http.conn.ssl.SSLSocketFactory.createSocket(SSLSocketFactory.java:388)
10-05 22:40:21.673: W/System.err(10007):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:214)
10-05 22:40:21.673: W/System.err(10007):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:167)
10-05 22:40:21.673: W/System.err(10007):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:125)
10-05 22:40:21.673: W/System.err(10007):    at org.apache.http.impl.client.DefaultRequestDirector.executeOriginal(DefaultRequestDirector.java:1227)
10-05 22:40:21.673: W/System.err(10007):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:677)
10-05 22:40:21.673: W/System.err(10007):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:567)
10-05 22:40:21.683: W/System.err(10007):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:491)
10-05 22:40:21.683: W/System.err(10007):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:469)
10-05 22:40:21.683: W/System.err(10007):    at com.maif.utility.ServiceHandler.makeServiceCall(ServiceHandler.java:83)
10-05 22:40:21.683: W/System.err(10007):    at com.maif.Visiter.jobrequests.JobsListLoader.loadInBackground(JobsListLoader.java:86)
10-05 22:40:21.683: W/System.err(10007):    at com.maif.Visiter.jobrequests.JobsListLoader.loadInBackground(JobsListLoader.java:1)
10-05 22:40:21.683: W/System.err(10007):    at android.support.v4.content.AsyncTaskLoader.onLoadInBackground(AsyncTaskLoader.java:242)
10-05 22:40:21.683: W/System.err(10007):    at android.support.v4.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:51)
10-05 22:40:21.683: W/System.err(10007):    at android.support.v4.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:40)
10-05 22:40:21.683: W/System.err(10007):    at android.support.v4.content.ModernAsyncTask$2.call(ModernAsyncTask.java:123)
10-05 22:40:21.683: W/System.err(10007):    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
10-05 22:40:21.683: W/System.err(10007):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
10-05 22:40:21.683: W/System.err(10007):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
10-05 22:40:21.683: W/System.err(10007):    at java.lang.Thread.run(Thread.java:841)
Pedro
  • 196
  • 3
  • 16
  • 1
    **What problem are you having?** Does it explode? – SLaks Sep 28 '14 at 14:33
  • @SLacks You are right, I had on the title "user" instead of "use". But anyway, on my explanation, I clearly mention what I am looking for: "I want to change my code on my APP to be able to connect through HTTPS and make that a safe connection to the webservice I have developed in PHP" So this means, whenever I try to get JSON response, I want that connection to be established through HTTPS and not HTTP. – Pedro Sep 28 '14 at 14:37
  • What did you try? What error did you get? – SLaks Sep 28 '14 at 14:37
  • I haven't saved the errors (maybe I should) but I tried several things (again, I'm a noob in Java). Here some: https://developer.android.com/training/articles/security-ssl.html http://developer.android.com/reference/javax/net/ssl/HttpsURLConnection.html http://stackoverflow.com/questions/16504527/how-to-do-an-https-post-from-android http://stackoverflow.com/questions/24397419/android-https-sni-support-using-sslcertificatesocketfactory?rq=1 http://stackoverflow.com/questions/12361090/server-name-indication-sni-on-java?rq=1 And some others... :( – Pedro Sep 28 '14 at 14:43
  • If you don't tell us what went wrong, all we can tell you is to try those exact things again, because they are the correct answers. – SLaks Sep 28 '14 at 14:58
  • @SLaks I updated my post inserting the error log after giving a lot of tries... :( – Pedro Oct 05 '14 at 21:44
  • Read the error message. Your server is sending the wrong certificate. – SLaks Oct 05 '14 at 21:46
  • It's a shared host and they told me that it's everything fine from their side since I already noticed that and sent them the error. But they confirmed everything is fine from their side... :( – Pedro Oct 05 '14 at 21:48

1 Answers1

0

You need to set up your HTTP client to use SNI (or, alternatively, get a dedicated IP address).

Exact details vary by Android version.
See this blog post.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • I already knew this solution, but even so, I thank you for your reply. Problem is, this does not help me since my APP is supported from Android 2.3 (Gingerbread) and above and the solution explained on that blog is for Android 4.2+ :( – Pedro Oct 05 '14 at 22:06
  • Are you sure? http://stackoverflow.com/a/5895320/34397 If so, you need a dedicated IP address. – SLaks Oct 05 '14 at 23:10
  • Well, in that case, I definitely need a dedicated IP address! :( Thank you. – Pedro Oct 06 '14 at 00:18