HttpClient的连接到HTTPS服务器 [英] HttpClient connecting to Https server

查看:120
本文介绍了HttpClient的连接到HTTPS服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在连接到HTTPS服务器通过跳过SSL证书(我的意思是允许所有主机)。
洛在这样的HTTPS服务器后我们需要每次登录火GET或POST请求。

While connecting to https server by skipping the SSL certificates(I mean allow all hosts) . After loggin in to such https server do we need to login everytime to fire get or post requests.

我在android系统尝试这种。
任何好的指针将是有益的。

I am trying this in android. Any good pointers would be helpful.

登录到HTTPS使用服务器的HttpClient(允许所有跳过SSL)
消防登录后简单的GET请求。

Login to https server using httpclient(Skip SSL by allowing all) Fire the simple Get request after login.

有没有这个简单的场景任何样品code基地。

Is there any sample code base for this simple scenario.

推荐答案

你必须把你的code在一个异步任务,因为网络电话没有在主线程上运行的第一次。

First of all you have to place your code in an async task as network calls don't run on the main thread.

然后就可以用这个东西是这样的:

Then you can use this something like this:

private RegistrationInfo AsyncRegisterDevice(
                AndroidDeviceInfo deviceInfo, NetworkIdentification networkId, long NMEC) {
            RegistrationInfo reqResp = new Objects().new RegistrationInfo();

            try {

                JSONStringer deviceRegistration = new JSONStringer().object()
                        .key("DeviceInfo").object().key("androidId")
                        .value(deviceInfo.androidId).key("imei")
                        .value(deviceInfo.imei).key("mac")
                        .value(deviceInfo.mac).key("brand")
                        .value(deviceInfo.brand).key("product")
                        .value(deviceInfo.product).key("model")
                        .value(deviceInfo.model).key("manufacturer")
                        .value(deviceInfo.manufacturer).key("device")
                        .value(deviceInfo.device).key("serial")
                        .value(deviceInfo.serial).key("carrierNumber")
                        .value(deviceInfo.carrierNumber).endObject()
                        .key("UserIdentification").object().key("userName")
                        .value(networkId.username).key("password")
                        .value(networkId.password).endObject()
                        .key("nmec").value(NMEC).endObject();

                HttpPost request = new HttpPost(hostProtocol + "://"
                        + hostAddress + "/Services/Register.svc/Register");
                request.setHeader("Accept", "application/json");
                request.setHeader("Content-Type", "application/json");

                StringEntity requestEntity = new StringEntity(
                        deviceRegistration.toString());

                request.setEntity(requestEntity);

                DefaultHttpClient httpClient = (DefaultHttpClient) CSRHttpClient
                        .getNewHttpClient();

                String message = new String();
                HttpEntity responseEntity = null;

                try {
                    HttpResponse httpResponse = httpClient.execute(request);
                    responseEntity = httpResponse.getEntity();
                } catch (Exception ex) {
                    message = ex.getMessage();
                    android.util.Log.e("CSR", message);
                    return new Objects().new RegistrationInfo();
                }

                if (responseEntity == null)
                    return reqResp;

                char[] buffer = new char[(int) responseEntity
                        .getContentLength()];
                InputStream stream = responseEntity.getContent();
                InputStreamReader reader = new InputStreamReader(stream);
                reader.read(buffer);
                stream.close();

                JSONObject jsonRegInfo = new JSONObject(new String(buffer));

                long androidId = jsonRegInfo.getLong("androidRegistrationId");
                long userId = jsonRegInfo.getLong("userRegistrationId");
                String token = jsonRegInfo.get("registrationToken").toString();

                reqResp.androidRegistrationId = androidId;
                reqResp.registrationToken = token;
                reqResp.userRegistrationId = userId;

            } catch (JSONException jsonEx) {
                String message = jsonEx.getMessage();
            }

            catch (NullPointerException n) {
                String message = n.getMessage();
            } catch (Exception ex) {
                String message = ex.getMessage();
            }
            return reqResp;
        }
    }

这code,使一个JSON请求到WCF web服务,并得到它到底解析到一个特定的对象,然后返回一个JSON响应。

This code makes a JSon request to a WCF webservice and gets a JSon response which is parsed in the end to a specific object that is then returned.

public class CSRHttpClient {

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

            SSLSocketFactory sf = new CSRSSLSocketFactory(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 ex)
        {
            return new DefaultHttpClient();
        }

    }


}

本类只供应到实例自定义套接字工厂允许接受所有有效和无效的服务器证书。这是不建议在敏感信息服务/运输这样的做法incurr,因为接受为有效的所有证书允许中间人攻击,其他的一些漏洞。

This class serves only to instance a Custom Socket Factory which allows to accept all valid and invalid server certificates. It is not advised to incurr in such practices on sensitive information services / transports, because accepting all certificates as valid allows a man-in-the-middle attack, as some other vulnerabilities.

希望这有助于你。

好运。

这篇关于HttpClient的连接到HTTPS服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆