酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

java使用curl请求对接接口

要在Java中使用curl请求对接接口,你可以使用`java.net.HttpURLConnection`类。以下是一个简单的示例: ```java import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class CurlRequest { public static void main(String[] args) { try { String url = "https://api.example.com/data"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // 设置请求方法 con.setRequestMethod("GET"); // 添加请求头 con.setRequestProperty("User-Agent", "Mozilla/5.0"); // 获取响应码 int responseCode = con.getResponseCode(); System.out.println("Response Code : " + responseCode); // 读取响应内容 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // 输出结果 System.out.println(response.toString()); } catch (Exception e) { e.printStackTrace(); } } } ``` 这个示例中,我们向`https://api.example.com/data`发送了一个GET请求,并将响应内容打印到控制台。你可以根据需要修改URL和请求方法。 [2024-05-30 16:36:20 | AI写代码神器 | 389点数解答]

相关提问