php - Android:使用 SSL/HTTPS 与 PHP 连接到数据库并使用 POST/GET

标签 php android mysql ssl https

我曾经使用 HTTP 连接到 php for mysql,现在我被要求使用 HTTPS,因为它更安全。但我尝试了太多方法但无法让平板电脑发布或获取任何信息,我制作了一个自签名证书并添加到本地计算机信任区域所以我不会被问到它没有被验证我想继续吗,我尝试通过浏览器连接并且它工作正常并打印了我需要的所有信息,但不是通过应用程序。我附上了我以前需要更改为 HTTPS 的 HTTP 代码。需要一些帮助来将此连接更改为 HTTPS。

    httpclient = new DefaultHttpClient();
    httppost = new HttpPost ("http://xx.xx.xx.xx/E-MENU/login.php");        
    username = etUser.getText().toString();
    password = etPass.getText().toString();
    password = md5(SHA1(password));

try{
    nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("username", username));
    nameValuePairs.add(new BasicNameValuePair("password", password));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    response = httpclient.execute(httppost);


if(response.getStatusLine().getStatusCode() == 200){
    entity = response.getEntity();
        if (entity!= null){

InputStream instream = entity.getContent();
JSONObject jsonResponse = new JSONObject (convertStreamToString(instream));

最佳答案

Log.e("body", body);
            HttpClient httpclient = getNewHttpClient();

            HttpPost httppost = new HttpPost("https://www.demo.com/login.php");

             nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));


            httppost.setEntity(entity);
            response = httpclient.execute(httppost);;


            Log.e("response", response.getStatusLine().toString());
            String aaa = response.getStatusLine().toString();
            Toast.makeText(getApplicationContext(), "Content :"+ aaa, Toast.LENGTH_LONG).show();
            HttpEntity entity1 = response.getEntity();
            is = entity1.getContent();

                //Toast.makeText(getApplicationContext(), "Content :"+ (CharSequence) is, Toast.LENGTH_LONG).show();

        }catch(Exception e){
            Log.e("log_tag", "Error in http connection "+e.toString());
        }


public HttpClient getNewHttpClient() {
        try {
            KeyStore trustStore = KeyStore.getInstance(KeyStore
                    .getDefaultType());
            trustStore.load(null, null);

            SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

            HttpParams params = new BasicHttpParams();
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

            SchemeRegistry registry = new SchemeRegistry();
            registry.register(new Scheme("http", PlainSocketFactory
                    .getSocketFactory(), 80));
            registry.register(new Scheme("https", sf, 443));

            ClientConnectionManager ccm = new ThreadSafeClientConnManager(
                    params, registry);

            return new DefaultHttpClient(ccm, params);
        } catch (Exception e) {
            return new DefaultHttpClient();
        }
    }

MySSLSocketFactory.java

public class MySSLSocketFactory extends SSLSocketFactory {
    SSLContext sslContext = SSLContext.getInstance("TLS");

    public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
        super(truststore);

        TrustManager tm = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        sslContext.init(null, new TrustManager[] { tm }, null);
    }

    @Override
    public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
        return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
    }

    @Override
    public Socket createSocket() throws IOException {
        return sslContext.getSocketFactory().createSocket();
    }
}

如果您在 4.0 以上工作,请在您的代码中添加此内容

 StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
         StrictMode.setThreadPolicy(policy);

关于php - Android:使用 SSL/HTTPS 与 PHP 连接到数据库并使用 POST/GET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15157238/

相关文章:

php - 如何使用$.ajax()上传文件

PHP:长字符串、json_encode、var_dump 和 echo

php - 这个 Yii 错误 #8192 是什么意思?

php - openshift DB 配置导致 503

javascript - 带有 echo &lt;script&gt; 的 ajax 代码不起作用

android - 如何检查是否在 Android 的 UI 线程上运行?

android - 无法为类型com.android.build.gradle.internal.dsl.NdkOptions的对象获取未知属性 'arm64-v8a'

android - 在 Android 上构建 libloc_api

php - MySQL - 单个 DATETIME 或单独的 DATE 和 TIME 列?

c++ - C++ 中的 mySQL 查询