android - 如何在 Android 中使用 HTTPS,共享 IP 主机

标签 android ssl sni

我需要什么:通过 HTTPS 连接获取 JSON 结果

我所拥有的:具有有效 SSL 证书的共享服务器

我想要的:能够建立 HTTPS 连接,但我做不到,因为当我用我找到的在线示例更改我的代码时,它永远无法工作...

详情:

几天来我一直在寻找解决方案,但我发现了很多不同的东西,并且已经在我的代码中尝试了很多不同的组合,但没有任何效果。 :(

我习惯于使用 PHP、MySQL、CSS、HTML 进行开发,但直到最近我才开始使用 Android (java),而且我从来没有开发过任何东西(甚至连“Hello world!”都没有)。

我想要一个简单的应用程序,然后我聘请了一个自由职业者(优秀的印度人,实际上......我认为自己很幸运)。

所以,我最近为我的网站购买了一个 SSL/TLS 证书,该证书位于共享服务器上,我想更改我的应用程序上的代码,以便能够通过 HTTPS 进行连接,并使其成为与网络服务的安全连接我用 PHP 开发过。

HTTP 请求一切正常,但是当我尝试在网上找到的一些不同的 HTTPS 建议时,没有任何效果。 :(

对此永远无法得出结论。哈哈

这是我在大约 30 个不同屏幕中的一个代码:

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

}

编辑:

这里是尝试一些事情后的错误:

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)

最佳答案

您需要将 HTTP 客户端设置为使用 SNI(或者,获取专用 IP 地址)。

具体细节因 Android 版本而异。
参见 this blog post .

关于android - 如何在 Android 中使用 HTTPS,共享 IP 主机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26085868/

相关文章:

android - UpdateAppWidget 空指针异常

android - ListView 导航就像在 android 联系人 View 中一样

ssl - 部署错误(证书链错误)

java - 在 Dataflow 中运行 Apache Beam Pipeline 时出现 SSLHandshakeException

java - 找不到 SNIServerName 类

java - 使用 Java8 的 SNI 客户端之谜

java - 如何在 Android 单元测试中模拟 Bundle 方法?

java - Android Studio - 视频应用程序崩溃 - Videoview 和 Mediaplayer - 无法播放录音

python - 在 python 2.7 中更新 openssl

apache - SNI 动态证书