JAVA使用HTTP代码示例模板

以下是一个使用Java发送HTTP请求的示例代码:

```java

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;

public class HttpExample {

public static void main(String[] args) {

try {

URL url = new URL("http://www.example.com/api");

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setRequestMethod("GET");

conn.setRequestProperty("Accept", "application/json");

if (conn.getResponseCode() != 200) {

throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());

}

BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

String output;

System.out.println("Output from Server .... \n");

while ((output = br.readLine()) != null) {

System.out.println(output);

}

conn.disconnect();

} catch (Exception e) {

e.printStackTrace();

}

}

}

```

这个示例代码使用了Java的HttpURLConnection类来发送HTTP请求。它发送了一个GET请求到指定的URL,并设置了Accept头部为application/json。如果响应码不是200,就会抛出一个运行时异常。最后,它从响应中读取数据并打印到控制台上。

你可能感兴趣的:(java,http,servlet,网络,网络协议)