欢迎光临
我们一直在努力

java使用okhttp库实现Authorization认证请求

<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>3.9.1</version>
</dependency>
import okhttp3.*;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

public class HttpUtil {
    static public OkHttpClient client;

    static private Logger logger = Logger.getLogger(HttpUtil.class);

    static {

        client = new OkHttpClient.Builder()

                .connectTimeout(10000L, TimeUnit.MILLISECONDS)

                .readTimeout(10000L, TimeUnit.MILLISECONDS)

                .build();

    }

    /**
     47
     * 同步GET请求 带Authorization认证
     48
     */

    public static String okhttp_get(String get_url, HashMap<String, Object> get_data, String[] auth_base){


        final String credential = Credentials.basic(auth_base[0], auth_base[1]);

        String result = "";

        String data_params = generateParameters(get_data);

        String data_url = get_url + data_params;

        Request request = new Request.Builder()

                .url(data_url)

                .header("Authorization", credential)

                .get()

                .build();

        Call call = client.newCall(request);

        try {

            Response response = call.execute();

            //判断是否成功
            if (response.isSuccessful()){
                result = response.body().string();
            }else {
                return "请求失败";
            }
            logger.debug(result);


        } catch (Exception e) {

            logger.error("网络GET请求失败!提示信息:"+e.getMessage());

        }

        return result;

    }
    /**
     * Post请求 带Authorization认证
     * */
    public static String okhttp_post(String get_url, HashMap<String, Object> get_data, String[] auth_base){

        final String credential = Credentials.basic(auth_base[0], auth_base[1]);

        String result = "";

        RequestBody fromBody = generateParametersForPost(get_data).build();


        Request request = new Request.Builder()

                .url(get_url)

                .header("Authorization", credential)

                .post(fromBody)

                .build();

        Call call = client.newCall(request);

        try {

            Response response = call.execute();

            //判断是否成功
            if (response.isSuccessful()){
                result = response.body().string();
            }else {
                return "请求失败";
            }
            logger.debug(result);


        } catch (Exception e) {

            logger.error("网络GET请求失败!提示信息:"+e.getMessage());

        }

        return result;

    }

    //拼接参数

    private static String generateParameters(HashMap<String, Object> parameters) {

        String urlAttachment = "";

        if(parameters.size()>0){

            urlAttachment = "?";

            Object[] keys = parameters.keySet().toArray();

            for(Object key : keys)

            urlAttachment += key.toString() + "=" + parameters.get(key).toString() + "&";

            urlAttachment = urlAttachment.substring(0,urlAttachment.length()-1);
        }

        return urlAttachment;
    }

    //拼接参数用于POST请求

    private static FormBody.Builder generateParametersForPost(HashMap<String, Object> parameters) {

        FormBody.Builder builder = new FormBody.Builder();

        if(parameters.size()>0){
            Object[] keys = parameters.keySet().toArray();

            for(Object key : keys){
                Object ff = parameters.get(key);
                String aa = parameters.get(key).toString();

                builder.add(key.toString(),parameters.get(key).toString());
            }
        }

        return builder;
    }

    /**
     * 发送私密API请求
     *
     * @paramget_url请求地址
     * @paramget_data 请求参数列表
     * @return          返回JSON数据
     */
    private String auth_get(){
        String result = "";
        String api_key = "apikey";
        String api_secret = "apisecret";
        //认证信息
        String[] baseauth = {api_key,api_secret};
        //请求的URL的参数
        HashMap<String, Object> get_data = new HashMap<>();
        get_data.put("page","1");       //page参数
        get_data.put("name","test");  //name参数
        result = HttpUtil.okhttp_get("http://www.superl.org/page-about.html", get_data, baseauth);
        return result;
    }


}

未经允许不得转载:ITyet » java使用okhttp库实现Authorization认证请求

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
打开看板娘