Java调用第三方接口(get/post)

本文介绍了如何在Maven项目中使用HttpClient进行HTTP请求,包括POST和GET方法,并结合Fastjson处理JSON数据,重点展示了SHA1加密和参数转换过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

新建maven工程,在pom.xml中导入httpclient与fastjson包,httpclient用来请求,fastjson进行参数转换与处理数据。

主方法

SHA1算法加密

POST 方法

利用 HttpClientBuilder创建连接对象

public static String postMethod(String url, JSONObject json){
    try {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        post.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
        StringEntity s = new StringEntity(json.toString());
        s.setContentEncoding("UTF-8");
        //发送json数据需要设置contentType
        s.setContentType("application/x-www-form-urlencoded");
        post.setEntity(s); //设置请求参数
        HttpResponse response = httpClient.execute(post);
        int statusCode = response.getStatusLine().getStatusCode();
        if (HttpStatus.SC_OK == statusCode){
            //返回String
            String res = EntityUtils.toString(response.getEntity());
            System.out.println(res);
            return res;
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

GET方法 

利用 HttpClientBuilder创建连接对象

public static String getMethod(String url){
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    HttpGet get = new HttpGet(url);
    try{
        //这里可以设置请求参数,token等
        get.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
        HttpResponse response = httpClient.execute(get);//执行获取响应
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){//根据状态码处理
            //返回字符串
            String res = EntityUtils.toString(response.getEntity());
            System.out.println(res);
            return res;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

参数处理与解析数据

获得的响应参数可以使用json‘进行分析,[ ]为数组,{ }为对象,利用 JSONObject.parseObject(String text)将字符串转为json对象,调用getJSONArray(key)获取json数组JSONArray,getString(key)获取对应的值,getJSONObject()获取json对象。可以根据json结构层层解析,获取需要的数据。
新建json对象,调用put方法可以赋值,之后作为请求参数设置。

### Java 中通过 GETPOST 方法调用第三方 API #### 使用 `HttpURLConnection` 类发送 HTTP 请求 在 Java 中可以利用原生的 `java.net.HttpURLConnection` 来发起网络请求。对于 GETPOST 请求来说,主要区别在于设置连接属性以及处理数据的方式。 针对 GET 请求: ```java URL url = new URL("http://example.com/api?param=value"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); // 设置请求方式为GET // 添加必要的HTTP头部信息 conn.setRequestProperty("Accept", "application/json"); int responseCode = conn.getResponseCode(); // 获取响应码 if(responseCode == HttpURLConnection.HTTP_OK){ BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; StringBuilder content = new StringBuilder(); while ((inputLine = in.readLine()) != null) { content.append(inputLine); } in.close(); System.out.println(content.toString()); // 输出返回的内容 } else{ System.out.println("GET request failed."); } ``` 上述代码展示了如何构建一个简单的 GET 请求并读取服务器端传回的数据[^1]。 而对于 POST 请求,则需额外准备要提交的数据体,并将其写入到输出流中去: ```java String param = "key1=value1&key2=value2"; // 参数字符串形式 URL url = new URL("http://example.com/postApiEndpoint"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); // 启用输出模式 conn.setRequestMethod("POST"); // 设置请求方式为POST conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); OutputStream os = conn.getOutputStream(); os.write(param.getBytes()); os.flush(); os.close(); BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8)); StringBuilder response = new StringBuilder(); String responseLine; while((responseLine = br.readLine())!=null){ response.append(responseLine.trim()); } System.out.println(response.toString()); br.close(); ``` 这段程序说明了怎样构造带有表单参数的 POST 请求,并接收来自服务端的信息作为回应[^2]。 为了简化开发过程中的重复劳动,通常会创建专门用于封装这些操作的帮助函数或是工具类来统一管理不同类型的 HTTP 请求逻辑[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值