Okhttp javax.net.ssl.sslexception:由peer关闭的连接

时间:2017-04-25 02:59:42

标签: java android okhttp

我打电话给api支付费用:https://test-api.pin.net.au/1/cards/

我试着邮递员,这很好。

当我用okhttp 2.7.5

应用到代码android时

我的代码:

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

    });

但是它不起作用并且问题:javax.net.ssl.SSLException:连接被对等关闭

1 个答案:

答案 0 :(得分:1)

连接到https服务器时,OKhttp需要知道要提供哪些TLS版本和密码套件。以下是与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();
祝你好运!!!