Send Json to server (nginx) as String - retrofit 2

2019-08-28 06:42发布

I am connecting to web service with last version retrofit but get me bellow error :

okhttp3.internal.http2.StreamResetException: stream was reset: PROTOCOL_ERROR

Is this error okhttp3.internal.http2.StreamResetException: stream was reset: CANCEL for huge string ? or for **nginx** of server ?

My code is like bellow :

try {
    // Create a trust manager that does not validate certificate chains
    final TrustManager[] trustAllCerts = new TrustManager[]{
        new X509TrustManager() {
            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) 
            throws CertificateException {}

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) 
            throws CertificateException {}

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return new java.security.cert.X509Certificate[]{};
                }
            }
        };

    // Install the all-trusting trust manager
    final SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
    // Create an ssl socket factory with our all-trusting manager
    final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
    builder.hostnameVerifier(new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    });

    OkHttpClient okHttpClient = builder.build();
    Retrofit retrofit = new Retrofit.Builder()
                            .baseUrl("https://xxx")
                            .client(okHttpClient)
                    .addConverterFactory(GsonConverterFactory.create())
                .addConverterFactory(ScalarsConverterFactory.create())
                .build();
    final PublicApi request = retrofit.create(PublicApi.class);
    Call<GetStatusSaveContactListModel> call = request.sendContactLists("saveContactList", obj.toString());
    call.enqueue(new Callback<GetStatusSaveContactListModel>() {
        @Override
        public void onResponse(@NonNull Call<GetStatusSaveContactListModel> call, @NonNull
            Response<GetStatusSaveContactListModel> response) {}

        @Override
        public void onFailure(@NonNull Call<GetStatusSaveContactListModel> call, Throwable t) {}
        });

} catch (Exception e) {
    throw new RuntimeException(e);
}

And :

@POST("/web_service/mobile/rest")
Call<GetStatusSaveContactListModel> sendContactLists(@Query("function") String function,
                                                     @Query("data") String data);

And :

implementation 'com.google.code.gson:gson:2.8.2'
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.10.0'
implementation 'com.squareup.retrofit2:converter-scalars:2.3.0'

I am sending a huge json as string to server :

{
    "userData": {
        "userId": "",
        "s_code": "24557878"
    },
    "contactList": [{
        "fname": "fffname",
        "lname": "llname",
        "name_prefix": "d",
        "middle_name": "a",
        "name_suffix": "z",
        "mobile": "09232446557",
        "emails": "sm.qa@yhgj.com"
    }, {
        "fname": "1fffname",
        "lname": "1llname",
        "name_prefix": "1d",
        "middle_name": "1a",
        "name_suffix": "1z",
        "mobile": "109232446557",
        "emails": ""
    },
     ...............]
} 

1条回答
倾城 Initia
2楼-- · 2019-08-28 07:40

I have no experience with Retrofit 2.+, but in Retrofit 1.9 to send json to server as a String in a POST request I have been forced to envelop it in TypedJsonString

import retrofit.mime.TypedString;

public class TypedJsonString extends TypedString {
    public TypedJsonString(String body) {
        super(body);
    }

    @Override public String mimeType() {
        return "application/json";
    }
}

and use this interface definition:

@POST(BASE_METHOD)
Response postProductRequest(@Body TypedJsonString productRequest); 

to make a request from the background thread:

String requestBody = new Gson().toJson(new ProductRequest());
retrofit.client.Response r = mApiService.postProductRequest(new TypedJsonString(requestBody));
查看更多
登录 后发表回答