Http请求调用第三方接口

1.http的post请求调用第三方接口

注意拼接http请求的两点要素:请求头、请求体

1.1 基本调用第三方接口的http请求

//1,获取httpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//2,声明请求类型
//HttpGet httpGet = new HttpGet("URL");
HttpPost httpPost = new HttpPost("接口的URL地址");
//3,设置访问http接口时所需的请求头信息
httpPost.addHeader("");
//4,设置访问http接口时所需的参数信息(请求体) httpPost.setEntity();
//4.1 发送JSON数据类型数据
JSONObject json = new JSONObject();
json.put("键","值");
json.put("键","值");
httpPost.setEntity(new StringEntity(json.toString(),"UTF-8"));
//4.2 发送普通类型的参数
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
        for(String key:json.keySet()) {
            parameters.add(new BasicNameValuePair(key, json.getString(key)));
        }       
// 将Content-Type设置为application/x-www-form-urlencoded类型
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters, "UTF-8");
httpPost.setEntity(formEntity);

//5,发送请求
CloseableHttpResponse response = httpClient.execute(httpPost);

//6,获取响应信息
//6.1获取响应的状态码response.getStatusLine().getStatusCode()
if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();
            
            // 获取返回的信息
            String string = EntityUtils.toString(entity, "UTF-8");           System.out.println(string);
        }

//7,关闭资源
response.close();
httpClient();
完整代码:

public class HttpClientUtil {

	//发送请求的url
    public static String url = "http://192.168.9.247:3080/co/cmd/deleteProject";

    public static void deletePost() throws IOException {
    
        // 获取HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 声明Post请求
        HttpPost httpPost = new HttpPost(url);

        // 设置请求头,在Post请求中限制了浏览器后才能访问
        httpPost.addHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36");
        httpPost.addHeader("Accept", "*/*");
        httpPost.addHeader("Accept-Encoding", "gzip, deflate, br");
        httpPost.addHeader("Content-Type", "application/json");
//        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
        httpPost.addHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");
        httpPost.addHeader("Connection", "keep-alive");
        
        // 设置token
        //httpPost.addHeader("Authorization","eyJ0eXAiOiJKV1QiLCJhbGciOiJIDASDUzI1NiJ9.eyJleHAiOjE2Mjc0NTQzODYsInVzZXJuYW1lIjoiYWJjZCJ9.MYvNg03txeNm_KiI27fdS0KViVxWhLntDjBjiP44UYQDASCSACCSA");

     JSONObject json = new JSONObject();
     json.put("filePath","js");
     json.put("projectId","61020ccdfd33d86b6abe8745");
     json.put("type","fileFolder");
     
     // 发送 json 类型数据,通过new StringEntity(),可将Content-Type设置为text/plain类型
        httpPost.setEntity(new StringEntity(json.toString(),"UTF-8"));

     // 设置参数(发送 普通参数 数据类型)
     /*
        List<NameValuePair> parameters = new ArrayList<NameValuePair>();
        for(String key:json.keySet()) {
            parameters.add(new BasicNameValuePair(key, json.getString(key)));
        }
        
        // 将Content-Type设置为application/x-www-form-urlencoded类型
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters, "UTF-8");
        httpPost.setEntity(formEntity);
		*/
        // 发送请求
        CloseableHttpResponse response = httpClient.execute(httpPost);
        
        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();
            
            // 获取返回的信息
            String string = EntityUtils.toString(entity, "UTF-8");
            System.out.println(string);
        }
        else
        {
            System.out.println("删除失败,请重试!!!");
        }

        // 关闭response、HttpClient资源
        response.close();
        httpClient.close();
    }
}

1.2 利用Hutool工具调用第三方接口的Http请求

String url = "url地址";//接口url地址信息
Map<String , String> header = new HashMap<>();
header.put("键","值");//请求头信息
JSONObject jsonObject = new JSONObject();
jsonObject.put("access_key",access_key);//请求体信息

//Hutool工具调用第三方接口(建造者模式)
HttpResponse execute = HttpUtil
.createPost(url)    .addHeaders(headers)
.body(jsonObject)
.execute();//execute()为方法调用接口"执行方法"
//后接body()方法可直接获取

//判断调用接口是否成功
if(!execute.isOK()){
    log.warn("调用接口失败的日志");
}
//调用成功可以获取响应信息
String respBody = execute.body();

//对响应信息进行操作
JSONArray array = JSONArray.fromObject(respBody);

for (Object o : array) {
            net.sf.json.JSONObject json = (net.sf.json.JSONObject) o;
            String code = json.getString("code");
    
     if ("ok".equals(code)) {
         //调用成功的操作
     }else{
         //调用失败的操作
     }
}  

注意:“ok”.equals(code)

进行比较时equals进行字符串进行比较时,应使用"常量字符串.equals(字符串变量)"

这样可以避免空指针异常

String a = abc;
String b = null;
if(b.equals("a")){      System.out.println("hhh");
}else{
 System.out.println("XXX");
}
//这样的操作会有空指针异常,因为一个null值无法进行字符串比较
if(a.equals("b")){      System.out.println("hhh");
}else{
 System.out.println("XXX");
}
//这样的操作会输出hhh
  • 3
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值