Java教程

java使用OkHttpClient发送get请求携带Header参数

本文主要是介绍java使用OkHttpClient发送get请求携带Header参数,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

本文章使用OkHttpClient发送get请求携带Header参数,header里为鉴权的用户+密码

OkHttpClient返回json字符串转javaBean

import com.google.gson.Gson;
import com.xiaojukeji.mdata.framework.entry.rest.RestDataResponse;
import com.xiaojukeji.mdata.framework.error.CheckedException;
import com.xiaojukeji.mdata.framework.error.ExceptionMessage;
import okhttp3.ConnectionPool;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @Author test
 * @Description
 * @Date 2020/8/3
 **/
@Component
public class RemoteProxy implements InitializingBean{

    private static final Logger LOGGER = LoggerFactory.getLogger(RemoteProxy.class);

    private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

    @Value("${party3.integrity.alliance.username}") private String username;

    @Value("${party3.integrity.alliance.password}") private String password;

    @Value("${party3.integrity.alliance.path}") private String base_path_url;

    private static String BASIC_AUTH_TOKEN;

    /**
     * 组装Header参数中的鉴权信息(账号+密码方式)
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        String auth = username + ":" + password;
        byte[] encodedAuth = Base64.encodeBase64(
                auth.getBytes(DEFAULT_CHARSET));
        BASIC_AUTH_TOKEN = "Basic " + new String(encodedAuth);
    }

    /**
     * 调用方法
     */
    public boolean remote(String param){
        RestDataResponse restDataResponse = queryHttpGetMethod(param);
        return (Boolean)restDataResponse.getData();
    }

    /**
     * get请求,组装url,放入鉴权header
     * 返回值RestDataResponse为自定义javaBean,结构与返回值Json字符型保持一致
     */
    private RestDataResponse queryHttpGetMethod(String param){

        Request request = new  Request.Builder()
                .url(base_path_url + param)
                .addHeader("Authorization", BASIC_AUTH_TOKEN).build();
        // new client对象时注意配置的链接与超时时间,根据需要进行调整
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(1, TimeUnit.SECONDS)
                .readTimeout(3, TimeUnit.SECONDS)
                .build();

        try{
            Response response = client.newCall(request).execute();
            String body = response.body().string();
            //json字符串转javaBean
            Gson gson = new Gson();
            RestDataResponse restDataResponse = gson.fromJson(body, RestDataResponse.class);
            if(response.code() != 200 || Objects.isNull(restDataResponse)){
                throw new CheckedException(ExceptionMessage.newInstance(400,
                        "invoke remote integrity alliance api error"),"");
            }
            if(restDataResponse.getMeta().getCode() != 0){
                throw new CheckedException(ExceptionMessage.newInstance(restDataResponse.getMeta().getCode(),
                        "invoke remote integrity alliance api error,message:{}"),
                        restDataResponse.getMeta().getMessage());
            }
            return restDataResponse;
        }catch (Exception e){
            throw new CheckedException(ExceptionMessage.newInstance(400,
                    "invoke remote integrity alliance api error"),"");
        }
    }

}

这篇关于java使用OkHttpClient发送get请求携带Header参数的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!