Java 能够发送http请求的TCP连接
我正在尝试构建一个能够接收、处理和响应http请求的简单web服务器(TCP)。我已经在客户端和服务器之间建立了TCP连接,问题是,尽管我已经尝试过了,但我还没有成功地执行http请求。 以下是Java中的客户端和服务器代码: 客户端类:Java 能够发送http请求的TCP连接,java,http,tcp,Java,Http,Tcp,我正在尝试构建一个能够接收、处理和响应http请求的简单web服务器(TCP)。我已经在客户端和服务器之间建立了TCP连接,问题是,尽管我已经尝试过了,但我还没有成功地执行http请求。 以下是Java中的客户端和服务器代码: 客户端类: import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; im
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class SocketCliente {
private String hostname;
private int porta;
Socket socketCliente;
public SocketCliente(String hostname, int porta){
this.hostname = hostname;
this.porta = porta;
}
public void connect() throws UnknownHostException, IOException{
System.out.println("Tentando se conectar com "+hostname+":"+porta);
socketCliente = new Socket(hostname,porta);
System.out.println("A conexão foi realizada");
}
public void readResponse() throws IOException{
String userInput;
BufferedReader stdIn = new BufferedReader(new InputStreamReader(socketCliente.getInputStream()));
System.out.println("Responsta do servidor:");
while ((userInput = stdIn.readLine()) != null) {
System.out.println(userInput);
}
}
public static void main(String arg[]){
//Creating a SocketClient object
SocketCliente client = new SocketCliente ("localhost",30000);
try {
//trying to establish connection to the server
client.connect();
//if successful, read response from server
client.readResponse();
} catch (UnknownHostException e) {
System.err.println("A conexão não pode ser estabelecida.");
} catch (IOException e) {
System.err.println("Conexão não estabelecida, pois o servidor pode ter problemas."+e.getMessage());
}
}
}
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class SocketCliente {
private String hostname;
private int porta;
Socket socketCliente;
public SocketCliente(String hostname, int porta){
this.hostname = hostname;
this.porta = porta;
}
public void connect() throws UnknownHostException, IOException{
System.out.println("Tentando se conectar com "+hostname+":"+porta);
socketCliente = new Socket(hostname,porta);
System.out.println("A conexão foi realizada");
}
public void readResponse() throws IOException{
String userInput;
BufferedReader stdIn = new BufferedReader(new InputStreamReader(socketCliente.getInputStream()));
System.out.println("Responsta do servidor:");
while ((userInput = stdIn.readLine()) != null) {
System.out.println(userInput);
}
}
public void HTTPCliente() throws Exception{
PrintWriter out = new PrintWriter(new OutputStreamWriter(socketCliente.getOutputStream()));
System.out.println("GET / HTTP/1.1");
System.out.println("User-Agent: test/1.0");
System.out.println("Host: localhost");
System.out.println("Accept: */*");
}
public static void main(String arg[]){
//Creating a SocketClient object
SocketCliente client = new SocketCliente ("localhost",30000);
try {
//trying to establish connection to the server
client.connect();
//if successful, read response from server
client.readResponse();
try {
//se http obtiver sucesso
client.HTTPCliente();
} catch (Exception ex) {
Logger.getLogger(SocketCliente.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (UnknownHostException e) {
System.err.println("A conexão não pode ser estabelecida.");
} catch (IOException e) {
System.err.println("Conexão não pode ser feita por problemas no servidor."+e.getMessage());
}
}
服务器类
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketServidor {
private ServerSocket serverSocket;
private int porta;
public SocketServidor(int porta) {
this.porta = porta;
}
public void start() throws IOException {
System.out.println("Começando o servidor na porta:" + porta);
serverSocket = new ServerSocket(porta);
//Listen for clients. Block till one connects
System.out.println("Esperando o cliente");
Socket client = serverSocket.accept();
//A client has connected to this server. Send welcome message
sendMensagemDeBoasVindas(client);
}
private void sendMensagemDeBoasVindas(Socket cliente) throws IOException {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(cliente.getOutputStream()));
writer.write("A sua conexão com o SocketServidor foi feita");
writer.flush();
}
/**
* Creates a SocketServer object and starts the server.
*
* @param
*/
public static void main(String[] args) {
// Setting a default port number.
int portNumber = 30000;
try {
// initializing the Socket Server
SocketServidor socketServer = new SocketServidor(portNumber);
socketServer.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
我真的不知道如何发出http请求。我尝试过创建一个http类,尝试过从现有的客户机类发送请求,但到目前为止没有任何效果。所有的谷歌搜索都没有帮助
一位朋友也在尝试这样做,他告诉我,在客户机类建立连接之后,需要将请求从客户机类发送到服务器类。我该怎么做
拜托,你能帮我吗
@罗宾格林
客户端类:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class SocketCliente {
private String hostname;
private int porta;
Socket socketCliente;
public SocketCliente(String hostname, int porta){
this.hostname = hostname;
this.porta = porta;
}
public void connect() throws UnknownHostException, IOException{
System.out.println("Tentando se conectar com "+hostname+":"+porta);
socketCliente = new Socket(hostname,porta);
System.out.println("A conexão foi realizada");
}
public void readResponse() throws IOException{
String userInput;
BufferedReader stdIn = new BufferedReader(new InputStreamReader(socketCliente.getInputStream()));
System.out.println("Responsta do servidor:");
while ((userInput = stdIn.readLine()) != null) {
System.out.println(userInput);
}
}
public static void main(String arg[]){
//Creating a SocketClient object
SocketCliente client = new SocketCliente ("localhost",30000);
try {
//trying to establish connection to the server
client.connect();
//if successful, read response from server
client.readResponse();
} catch (UnknownHostException e) {
System.err.println("A conexão não pode ser estabelecida.");
} catch (IOException e) {
System.err.println("Conexão não estabelecida, pois o servidor pode ter problemas."+e.getMessage());
}
}
}
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class SocketCliente {
private String hostname;
private int porta;
Socket socketCliente;
public SocketCliente(String hostname, int porta){
this.hostname = hostname;
this.porta = porta;
}
public void connect() throws UnknownHostException, IOException{
System.out.println("Tentando se conectar com "+hostname+":"+porta);
socketCliente = new Socket(hostname,porta);
System.out.println("A conexão foi realizada");
}
public void readResponse() throws IOException{
String userInput;
BufferedReader stdIn = new BufferedReader(new InputStreamReader(socketCliente.getInputStream()));
System.out.println("Responsta do servidor:");
while ((userInput = stdIn.readLine()) != null) {
System.out.println(userInput);
}
}
public void HTTPCliente() throws Exception{
PrintWriter out = new PrintWriter(new OutputStreamWriter(socketCliente.getOutputStream()));
System.out.println("GET / HTTP/1.1");
System.out.println("User-Agent: test/1.0");
System.out.println("Host: localhost");
System.out.println("Accept: */*");
}
public static void main(String arg[]){
//Creating a SocketClient object
SocketCliente client = new SocketCliente ("localhost",30000);
try {
//trying to establish connection to the server
client.connect();
//if successful, read response from server
client.readResponse();
try {
//se http obtiver sucesso
client.HTTPCliente();
} catch (Exception ex) {
Logger.getLogger(SocketCliente.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (UnknownHostException e) {
System.err.println("A conexão não pode ser estabelecida.");
} catch (IOException e) {
System.err.println("Conexão não pode ser feita por problemas no servidor."+e.getMessage());
}
}
}您需要发送以下内容:
GET / HTTP/1.1
User-Agent: test/1.0
Host: localhost
Accept: */*
所以也许:
PrintWriter out = new PrintWriter(new OutputStreamWriter(socketCliente.getOutputStream()));
out.println("GET / HTTP/1.1");
out.println("User-Agent: test/1.0");
out.println("Host: localhost");
out.println("Accept: */*");
但顺便说一句,这是一种低级的、更复杂的方法。使用高级API更容易做到这一点。但我不知道,这可能是家庭作业中不允许的。请给我们看一下您试图从客户那里发送请求的代码。很抱歉,我现在没有它:很遗憾,我把它忘在了学校实验室的计算机上。好的。我在我的客户机类中尝试了这一点,但什么也没发生:它没有打印或给出错误。那么,服务器在这个过程中做什么呢?我如何让他得到这个请求?附言:谢谢你的回答!HTTP是一种协议,允许请求以特定资源为目标。因为您只有一个资源,所以可以忽略请求中的数据,但这是一种欺骗。因此,实际上您应该解析请求的第一行,从中提取URL(/在本例中),如果它是您期望的,则生成适当的HTTP响应。至于为什么什么都没发生,我不知道-请发布你的更新代码。抱歉耽搁了。我已经更新了代码。再次感谢您的帮助。对不起,这还不够详细。当你回到电脑前,请把实际的代码贴出来。是我现在带着的代码还是我留在学校的代码?因为我在学校的那一个我只能在星期三拿到。。。