网络编程难题:Java HTTP客户端和服务器端交互案例
在Java中,实现HTTP客户端和服务器端的交互涉及到Socket编程和HttpURLConnection等技术。以下是一个简单的例子,展示如何创建一个HTTP客户端向服务器发送GET请求。
客户端(使用Java的HttpURLConnection):
import java.io.BufferedReader;
import java.io.InputStreamReader;
import javax.net.ssl.HttpsURLConnection;
public class HttpClient {
public static void main(String[] args) throws Exception {
// 创建HTTPS连接
HttpsURLConnection httpsConn = (HttpsURLConnection)
new URL("https://example.com").openConnection();
// 设置请求方法为GET
httpsConn.setRequestMethod("GET");
// 获取并打印响应
int responseCode = httpsConn.getResponseCode();
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(httpsConn.getInputStream())));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null)) {
content.append(inputLine);
}
in.close();
System.out.println("Response Body : " + content.toString());
}
}
服务器端(使用Java的HttpServer):
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class HttpServer {
public static void main(String[] args) throws IOException {
// 创建服务器监听端口
ServerSocket serverSocket = new ServerSocket(8000);
System.out.println("Http Server is running on port 8000...");
// 等待客户端连接
Socket clientSocket = serverSocket.accept();
System.out.println("Received connection from " + clientSocket.getInetAddress().getHostAddress());
// 客户端发送请求,这里以GET为例
BufferedReader inFromClientSocket = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = inFromClientSocket.readLine()) != null)) {
content.append(inputLine);
}
// 向客户端发送响应
clientSocket.getOutputStream().write(content.toString());
clientSocket.close();
serverSocket.close();
}
}
这个例子中,客户端使用Java的HttpURLConnection向服务器发送GET请求。服务器端创建一个HttpServer实例监听8000端口,当接收到客户端请求时,返回响应内容。
还没有评论,来说两句吧...