php – 如何在android上使用SSL与多实体

以下是我如何使用appache将数据发布到Web URL的代码.应用程序与后端交互的主要逻辑是,将数据发布到URL( PHP),并且 PHP运行逻辑以使用数据库等……

那么,我想知道如何在其上实现SSL?或者我只需要将PHP程序和android端POST更改为以“https”而不是“http”开头的网站?谢谢

protected class FormHandler extends AsyncTask<Object,Void,JSONObject> {
        private FormListener listener;
        private ProgressDialog pd;

        public FormHandler() {
            pd = ProgressDialog.show(ctx,"",ctx.getResources().getString(R.string.loading),true);
        }

        @Override
        protected JSONObject doInBackground(Object... params) {

            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

            listener = (FormListener) params[0];

            // WordPress default parameter
            builder.addTextBody("_wpcf7","610");
            builder.addTextBody("_wpcf7_version","3.7.2");
            builder.addTextBody("_wpcf7_locale","en_US");
            builder.addTextBody("_wpcf7_unit_tag","wpcf7-f610-p611-o1");
            builder.addTextBody("_wpnonce","4ddf1f1d07");
            builder.addPart("your-firstname",new StringBody((String) params[1],ContentType.create("text/plain",Consts.UTF_8)));
            builder.addPart("your-lastname",new StringBody((String) params[2],Consts.UTF_8)));
            builder.addPart("your-email",new StringBody((String) params[3],Consts.UTF_8)));
            builder.addPart("your-question",new StringBody((String) params[4],Consts.UTF_8)));
            builder.addPart("your-details",new StringBody((String) params[5],Consts.UTF_8)));
            builder.addTextBody("_wpcf7_is_ajax_call","1");

            // Set timeout (1 minute)
            HttpParams httpParameters = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParameters,Constant.uploadTimeout);
            HttpConnectionParams.setSoTimeout(httpParameters,Constant.uploadTimeout);

            HttpClient client = new DefaultHttpClient(httpParameters);
            HttpPost post = new HttpPost(Constant.formURL);
            HttpEntity entity = builder.build();
            post.setEntity(entity);

            try {
                HttpResponse response = client.execute(post);
                BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(),"UTF-8"));
                StringBuilder strBuild = new StringBuilder();

                for (String line = null; (line = reader.readLine()) != null;) {
                    strBuild.append(line).append("\n");
                }

                String result = strBuild.toString().replace("<textarea>","").replace("</textarea>","");

                JSONTokener tokener = new JSONTokener(result);

                if (tokener != null)
                    return (new JSONObject(tokener));

            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 
            return null;
        }

        @Override
        protected void onPostExecute(JSONObject result) {
            if(pd != null) {
                pd.dismiss();
            }
            if(result != null)  {
                try {
                    if (result.getString("mailSent").equals("true"))
                        listener.submitComplete();
                    else
                        listener.submitFailure();
                } catch (JSONException e) {
                    listener.submitFailure();
                }
            } else {
                Utility.showErrorDialog(ctx,getResources().getString(R.string.sys_info),getResources().getString(R.string.err_submit),getResources().getString(R.string.close));
            }
        }
    }
// Http Client with SSL factory

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

// Post request for multi part entity

public void postRequest(){

    DefaultHttpClient httpClient = new getNewHttpClient();
    HttpPost postRequest = new HttpPost(url);
    String auth = "USER_NAME" + ":" + "PASSWORD";
    byte[] bytes = auth.getBytes();
    postRequest.setHeader("Authorization","Basic " + new String(Base64.encodeBytes(bytes)));

    try {
        MultipartEntity mpC = new MultipartEntity();
        FileBody fb = new FileBody(message);
        StringBody sbPicID = new StringBody(fb.getFilename());
        mpC.addPart("name",sbPicID);
        mpC.addPart("file",fb);
        postRequest.setEntity(mpC);
        HttpResponse res;
        res = httpClient.execute(postRequest);
        BufferedReader rd = new BufferedReader(new InputStreamReader(res.getEntity().getContent()));
        String resPictureId = "";
        resPictureId = rd.readLine();

        Session.put("PICTURE_"+position,resPictureId);
        res.getEntity().getContent().close();
    }catch (Exception e) {
        // TODO: handle exception
    }

}

// SSL factory class

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

}

相关文章

文章浏览阅读8.4k次,点赞8次,收藏7次。SourceCodester Onl...
文章浏览阅读3.4k次,点赞46次,收藏51次。本文为大家介绍在...
文章浏览阅读1.1k次。- php是最优秀, 最原生的模板语言, 替代...
文章浏览阅读1.1k次,点赞18次,收藏15次。整理K8s网络相关笔...
文章浏览阅读1.2k次,点赞22次,收藏19次。此网络模型提供了...
文章浏览阅读1.1k次,点赞14次,收藏19次。当我们谈论网络安...