Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/192.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何在android上使用多实体SSL_Php_Android_Ssl - Fatal编程技术网

Php 如何在android上使用多实体SSL

Php 如何在android上使用多实体SSL,php,android,ssl,Php,Android,Ssl,下面是我如何使用appache将数据发布到web URL的代码。应用程序与后端交互的主要逻辑是,将数据发布到URL(PHP),PHP运行该逻辑以处理数据库等 那么,我想知道如何在其上实现SSL?或者我只需要修改PHP程序,android端的帖子就可以发布到一个以“https”而不是“http”开头的网站上?谢谢 受保护的类FormHandler扩展了AsyncTask{ 私有窗体侦听器; 私营部门; 公共FormHandler(){ pd=ProgressDialog.show(ctx,“,ct

下面是我如何使用appache将数据发布到web URL的代码。应用程序与后端交互的主要逻辑是,将数据发布到URL(PHP),PHP运行该逻辑以处理数据库等

那么,我想知道如何在其上实现SSL?或者我只需要修改PHP程序,android端的帖子就可以发布到一个以“https”而不是“http”开头的网站上?谢谢

受保护的类FormHandler扩展了AsyncTask{
私有窗体侦听器;
私营部门;
公共FormHandler(){
pd=ProgressDialog.show(ctx,“,ctx.getResources().getString(R.string.loading),true);
}
@凌驾
受保护的JSONObject doInBackground(对象…参数){
MultipartEntityBuilder=MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_兼容);
listener=(FormListener)参数[0];
//Wordpress默认参数
生成器。添加文本体(“wpcf7”、“610”);
builder.addTextBody(“wpcf7版本”、“3.7.2”);
builder.addTextBody(“_wpcf7_locale”,“en_US”);
生成器.添加文本体(“wpcf7单元标签”,“wpcf7-f610-p611-o1”);
builder.addTextBody(“\u wpnce”,“4DDF1F07”);
builder.addPart(“您的名字”,新的StringBody((String)参数[1],ContentType.create(“text/plain”,Consts.UTF_8));
builder.addPart(“您的姓氏”,新的StringBody((String)参数[2],ContentType.create(“text/plain”,Consts.UTF_8));
builder.addPart(“您的电子邮件”,新的StringBody((String)参数[3],ContentType.create(“text/plain”,Consts.UTF_8));
builder.addPart(“您的问题”,新的StringBody((String)参数[4],ContentType.create(“text/plain”,Consts.UTF_8));
builder.addPart(“您的详细信息”,新的StringBody((String)参数[5],ContentType.create(“text/plain”,Consts.UTF_8));
addTextBody(“\u wpcf7\u是\u ajax\u调用”,“1”);
//设置超时(1分钟)
HttpParams httpParameters=新的BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters,常量.uploadTimeout);
HttpConnectionParams.setSoTimeout(httpParameters,常量.uploadTimeout);
HttpClient=新的默认HttpClient(httpParameters);
HttpPost=新的HttpPost(常量.formURL);
HttpEntity=builder.build();
后设实体(实体);
试一试{
HttpResponse response=client.execute(post);
BufferedReader=新的BufferedReader(新的InputStreamReader(response.getEntity().getContent(),“UTF-8”);
StringBuilder strBuild=新建StringBuilder();
for(String line=null;(line=reader.readLine())!=null;){
strBuild.append(行).append(“\n”);
}
字符串结果=strBuild.toString().replace(“,”).replace(“,”);
JSONTokener令牌=新的JSONTokener(结果);
if(标记器!=null)
返回(新JSONObject(标记器));
}捕获(客户端协议例外e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}捕获(IOE异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}捕获(JSONException e){
//TODO自动生成的捕捉块
e、 printStackTrace();
} 
返回null;
}
@凌驾
受保护的void onPostExecute(JSONObject结果){
如果(pd!=null){
pd.解散();
}
如果(结果!=null){
试一试{
if(result.getString(“mailssent”).equals(“true”))
listener.submitComplete();
其他的
listener.submitFailure();
}捕获(JSONException e){
listener.submitFailure();
}
}否则{
getResources().getString(R.string.sys_info),getResources().getString(R.string.err_submit),getResources().getString(R.string.close));
}
}
}

您使用ssl的目的是什么?有不同的用例:

  • SSL仅作为安全通信通道
  • SSL来验证您是否正在与正确的服务器通信
  • SSL,让服务器验证连接是否来自应用程序

对于前两个,您按照建议执行,但对于最后一个,您需要应用程序中的证书,然后Web服务器可以验证该证书。

嘿,您可以像下面那样实现SSL

       private HttpResponse getResponse(HttpPost request) {
    try {
        BasicHttpParams httpParams = new BasicHttpParams();

        ConnManagerParams.setTimeout(httpParams, connectionTimeout);
        HttpConnectionParams.setSoTimeout(httpParams, connectionTimeout);
        HttpConnectionParams.setConnectionTimeout(httpParams, connectionTimeout);
        HttpConnectionParams.setTcpNoDelay(httpParams, true);
        HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);

        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory socketFactory = new CustomSSLSocketFactory(trustStore);
        socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("https", socketFactory, Integer.parseInt(Constants.PORT_NUMBER)));
        ThreadSafeClientConnManager cManager = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

        HttpClient httpClient = new DefaultHttpClient(cManager, httpParams);
        return httpClient.execute(request);
    } catch (Exception e) {
        if (Constants.DEBUG) {
            Log.e(TAG, "", e);
        }
    }
    return null;
}
现在是CustomSSlSocketFactory.java

    import java.io.IOException;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import java.security.KeyManagementException;
    import java.security.KeyStore;
    import java.security.KeyStoreException;
    import java.security.NoSuchAlgorithmException;
    import java.security.UnrecoverableKeyException;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;

    import javax.net.ssl.SSLContext;
    import javax.net.ssl.TrustManager;
    import javax.net.ssl.X509TrustManager;

    import org.apache.http.conn.ssl.SSLSocketFactory;

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

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

    import java.io.IOException;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import java.security.KeyManagementException;
    import java.security.KeyStore;
    import java.security.KeyStoreException;
    import java.security.NoSuchAlgorithmException;
    import java.security.UnrecoverableKeyException;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;

    import javax.net.ssl.SSLContext;
    import javax.net.ssl.TrustManager;
    import javax.net.ssl.X509TrustManager;

    import org.apache.http.conn.ssl.SSLSocketFactory;

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

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

}