Sorting out Java related problems

Keywords: Java JSON

1. A large number of close ﹣ wait occurred in the okhttpclient call.

Problem location:

If there is a large number of close ﹣ wait in the system, it indicates that there is a problem in your code, that is, the connection is not closed.

In OkHttpClient, the default value of HTTP header field Connection is keep alive, which will cause the client to disconnect in time when the server disconnects, resulting in a large number of close and wait.

Problem modification:

Set the HTTP header field Connection to close

 

Here is a short link http call code.

package com.xman.httpclient;

import okhttp3.*;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * Created by wangyaofu on 2018/4/25.
 */
@Service
public class HttpServiceImpl {

    public final static int CONNECT_TIMEOUT =10000;
    public final static int READ_TIMEOUT=10000;
    public final static int WRITE_TIMEOUT=10000;

    public String httpGet(String url, String userAgent) {
            final Request request = new Request.Builder()
                    .url(url).header("User-Agent", userAgent).header("Connection", "close")
                    .build();
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .readTimeout(READ_TIMEOUT, TimeUnit.MILLISECONDS)
                    .writeTimeout(WRITE_TIMEOUT, TimeUnit.MILLISECONDS)
                    .connectTimeout(CONNECT_TIMEOUT, TimeUnit.MILLISECONDS)
                    .build();
        Response response;
        try {
            response = okHttpClient.newCall(request).execute();
            return response.body().string();
        } catch (Exception e) {
            //logger.error("httpGet err=" + e.getMessage());
        }
        return null;
    }

    public String httpPost(String url, String body) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), body);
        //Create a request object
        Request request = new Request.Builder()
                .url(url).header("Connection", "close")
                .post(requestBody)
                .build();
        //Send request to get response
        try {
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .readTimeout(READ_TIMEOUT, TimeUnit.MILLISECONDS)
                    .writeTimeout(WRITE_TIMEOUT, TimeUnit.MILLISECONDS)
                    .connectTimeout(CONNECT_TIMEOUT, TimeUnit.MILLISECONDS)
                    .build();
            Response response=okHttpClient.newCall(request).execute();
            if (response != null && response.body() != null) {
                return response.body().string();
            }
        } catch (Exception e) {
            //logger.error("httpPost err=" + e.getMessage());
        }
        return null;
    }
}

Posted by msnhockey on Sun, 01 Dec 2019 05:05:53 -0800