2024年6月3日发(作者:)

java请求url接口的方法

在Java中,可以使用``或第三方库如Apache HttpClient、OkHttp等来请

求URL接口。

下面是使用``的示例代码:

```java

import ;

import ;

import ;

import ;

public class HttpRequestExample {

public static void main(String[] args) throws Exception {

String url = "

HttpURLConnection connection = (HttpURLConnection) new

URL(url).openConnection();

("GET");

int responseCode = ();

("Response Code : " + responseCode);

BufferedReader in = new BufferedReader(new

InputStreamReader(()));

String inputLine;

StringBuffer response = new StringBuffer();

while ((inputLine = ()) != null) {

(inputLine);

}

();

("Response : " + ());

}

}

```

在这个例子中,我们使用`HttpURLConnection`来创建一个HTTP GET请

求,并从指定的URL获取响应。然后我们读取响应并打印出来。

如果你需要发送POST请求或需要设置其他HTTP头,你可以使用

`setRequestProperty`方法。例如:

```java

("Content-Type", "application/json");

(true); // 设置输出为true,表示要发送数据

OutputStream os = ();

("{"key":"value"}".getBytes()); // 发送JSON数据

();

```