TCP连接能够发送http请求

时间:2013-10-13 12:18:33

标签: 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;

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.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类,我尝试从现有的Client类发送请求,但到目前为止还没有任何工作。所有谷歌搜索都没有帮助。

一位正在尝试这样做的朋友告诉我,您需要在客户端已经建立连接后将请求从Client类发送到Server类。我该怎么做?

拜托,你能帮助我吗?

@罗宾绿 客户类:

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());
    }
}

}

1 个答案:

答案 0 :(得分:1)

您需要发送以下内容:

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更容易实现。但也许在家庭作业中不允许这样做,我不知道。