使用Java进行网络编程,HTTP请求与响应示例
在Java中,我们可以使用java.net和java.io包来实现HTTP请求与响应。以下是一个简单的示例,使用HttpURLConnection进行GET请求:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpGetExample {
public static void main(String[] args) {
String urlStr = "http://example.com/api/data"; // Replace with your API endpoint
try {
URL url = new URL(urlStr);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Set request method
connection.setRequestMethod("GET");
// Check if response code is 200 (OK)
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
// If the request was successful, read the response
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null)) {
content.append(inputLine);
}
in.close();
System.out.println("Response Content: " + content.toString());
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
注意:这个示例使用的是HttpURLConnection,这是Java中处理HTTP请求和响应的传统方式。如果需要更高级的API,如java.net.HttpClient,可能会更适合现代的网络编程需求。
还没有评论,来说两句吧...