HttpClient connecting to Https server

2020-08-01 08:53发布

问题:

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.

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

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

Is there any sample code base for this simple scenario.

回答1:

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

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

    }


}

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.

Hope this helps you.

Best of luck.



标签: android https