Nguyễn TrungHậu
Nguyễn TrungHậu

Reputation: 21

Okhttp javax.net.ssl.sslexception: connection closed by peer

I call api for pin payment : https://test-api.pin.net.au/1/cards/

I try on postman , it good work.

When i apply into code android with okhttp 2.7.5

My code :

OkHttpClient httpClient = new OkHttpClient();

    RequestBody requestBody = new FormEncodingBuilder()
            .add("publishable_api_key", BuildConfig.PIN_PAYMENT_PUBLISHABLE_KEY)
            .add("number", scanResult.cardNumber)
            .add("expiry_month", scanResult.expiryMonth+"")
            .add("expiry_year", scanResult.expiryYear+"")
            .add("cvc", scanResult.cvv)
            .add("address_postcode", scanResult.postalCode)
            .add("name", name).build();


    Request request = new Request.Builder()
            .url(BuildConfig.BASE_URL_PIN_PAYMENT + Constants.API_CARD_PIN_PAYMENT)
            .post(requestBody)
            .build();

    httpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            view.hideLoading();
            view.showError(e.getMessage());
        }

        @Override
        public void onResponse(Response response) throws IOException {
            view.hideLoading();
            if (!response.isSuccessful()){
                String body = "Something went wrong.Please try again later.";
                try {
                    JSONObject object = new JSONObject(response.body().string());
                    body = object.getString("error_description");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                view.showError(body);
            }else {
                view.hideLoading();
                Gson gson = new Gson();
                CardPinPaymentResponse paymentResponse = gson.fromJson(response.body().string() , CardPinPaymentResponse.class);
                view.getTokenCardSuccess(paymentResponse);
            }
        }

    });

But it not work and issue : javax.net.ssl.SSLException: Connection closed by peer

Upvotes: 1

Views: 5004

Answers (1)

Liem Vo
Liem Vo

Reputation: 5329

When you connect to https server the OKhttp needs to know which TLS versions and cipher suites to offer. Here is the example code to connect with https

    ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)  
    .tlsVersions(TlsVersion.TLS_1_2)
    .cipherSuites(
          CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
          CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
          CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256)
    .build();

OkHttpClient client = new OkHttpClient.Builder() 
    .connectionSpecs(Collections.singletonList(spec))
    .build();

Good luck!!!

Upvotes: 1

Related Questions