• 使用HttpUtils完成Http Basic 认证


    调用声网(agora)的远程接口(Restful Api)时,对方需要使用Basic Auth的方式进行认证(需要输入用户名和密码)。

    一,使用Postman完成基于Basic Auth的Http认证方式

    二,在代码中如何调用呢?

    1.当我们使用HttpUtil工具类模拟浏览器调用时,需要在header设置Authorization属性

    创建Http Get请求时,设置header。修改HttpUtil工具类中的Get方法,添加如下代码:

            // 创建http GET请求
           //修改前:
    //HttpGet httpGet = new HttpGet(uri);
           //---------------------------------------
           //修改后:

             HttpGet httpGet = new HttpGet(uri); List<NameValuePair> params = new ArrayList<NameValuePair>(); if(param==null){ params=null; } RequestBuilder requestBuilder = RequestBuilder.get().setUri(new URI(url)); requestBuilder.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8)); httpGet.setHeader( new BasicHeader("Content-Type", param.get("Content-Type"))); httpGet.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8")); httpGet.setHeader("Authorization",param.get("Authorization"));

    2.完整HttpUtil工具类:

    package com.yishang.utils;
    
    import org.apache.http.Consts;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.client.methods.RequestBuilder;
    import org.apache.http.client.utils.URIBuilder;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.message.BasicHeader;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.util.EntityUtils;
    
    import java.io.IOException;
    import java.net.URI;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    
    public class HttpUtils {
    
        public static String doGet(String url, Map<String, String> param) {
    
            // 创建Httpclient对象
            CloseableHttpClient httpclient = HttpClients.createDefault();
    
            String resultString = "";
            CloseableHttpResponse response = null;
            try {
                // 创建uri
                URIBuilder builder = new URIBuilder(url);
                if (param != null) {
                    for (String key : param.keySet()) {
                        builder.addParameter(key, param.get(key));
                    }
                }
                URI uri = builder.build();
    
                // 创建http GET请求
                //HttpGet httpGet = new HttpGet(uri);
    
                HttpGet httpGet = new HttpGet(uri);
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                if(param==null){
                    params=null;
                }
                RequestBuilder requestBuilder = RequestBuilder.get().setUri(new URI(url));
                requestBuilder.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));
                httpGet.setHeader(
                        new BasicHeader("Content-Type", param.get("Content-Type")));
                httpGet.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));
                httpGet.setHeader("Authorization",param.get("Authorization"));
    
    
    
                // 执行请求
                response = httpclient.execute(httpGet);
                // 判断返回状态是否为200
                if (response.getStatusLine().getStatusCode() == 200) {
                    resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (response != null) {
                        response.close();
                    }
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return resultString;
        }
    
        public static String doGet(String url) {
            return doGet(url, null);
        }
    
        public static String doPost(String url, Map<String, String> param) {
            // 创建Httpclient对象
            CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse response = null;
            String resultString = "";
            try {
                // 创建Http Post请求
                HttpPost httpPost = new HttpPost(url);
                // 创建参数列表
                if (param != null) {
                    List<NameValuePair> paramList = new ArrayList<>();
                    for (String key : param.keySet()) {
                        paramList.add(new BasicNameValuePair(key, param.get(key)));
                    }
                    // 模拟表单
                    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                    httpPost.setEntity(entity);
                }
                // 执行http请求
                response = httpClient.execute(httpPost);
                resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    response.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
    
            return resultString;
        }
    
        public static String doPost(String url) {
            return doPost(url, null);
        }
    }

    3.使用HttpUtil的Get方法调用声网的Restful Api:

        /*
        http的 basic Auth认证方式
        */
        String username = "yourusername";
        String password = "yourpassword";
        String userMsg = username + ":" + password;
        String base64UserMsg = Base64.encodeBase64String(userMsg.getBytes());
    
        String authorization="Basic "+base64UserMsg;
        String content_type = "application/x-www-form-urlencoded";
        Map<String,String> params = new HashMap<String, String>();
        params.put("Authorization", authorization);
        params.put("Content-Type", content_type);
    
        String url = "http://api.agora.io/dev/v1/projects";
        String resultProjects = HttpUtils.doGet(url,params);    
  • 相关阅读:
    C#新功能--命名参数与可选参数
    C#新功能--命名参数
    初识SqlLite ---.net连接数据库
    混合模式程序集是针对“v2.0.50727”版的运行时生成的,在没有配置其他信息的情况下,无法在 4.0 运行时中加载该...
    看到他我一下子就悟了-- 泛型(2)
    ExtJS4中设置tabpanel的tab高度问题
    java学习1-环境搭建
    oracle获取clob调优
    oracle job定时执行存储过程
    【转】【真正福利】成为专业程序员路上用到的各种优秀资料、神器及框架
  • 原文地址:https://www.cnblogs.com/inspred/p/10621645.html
Copyright © 2020-2023  润新知