Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How read HTTP response through sockets?

I'm trying create http proxy server on android device. When i trying read response from HTTP server (example1.com) ( example1.com contains content-length in header) If HTTP server contains content-length, then i'm read bytes from content-length else i'm read all bytes of response

byte[] bytes = IOUtils.toByteArray(inFromServer);

The problem is that, when response contains content-length the response reads quickly. If response not contains content-length the response read slowly.

this my code

DataInputStream in = new DataInputStream(inFromServer);
        //BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String line = "";
        String str = "";
        Integer len = 0;
        while(true) {
            line = in.readLine();
            if  (line.indexOf("Content-Length") != -1)
            {
                len = Integer.parseInt( line.split("\\D+")[1] );
                //System.out.println("LINEE="+len);
            }

            out.println(line);
            str = str + line + '\n';
            if(line.isEmpty())  break;
        }
        int i = Integer.valueOf(len);
        String body= "";
        System.out.println("i="+i);
        if (i>0) {
            byte[] buf = new byte[i];
            in.readFully(buf);
            out.write(buf);
            for (byte b:buf) {
                body = body + (char)b;
            }

        }else{

            byte[] bytes = IOUtils.toByteArray(inFromServer);
            out.write(bytes);
        }

out - outStream to browser

like image 470
Petr Avatar asked Feb 11 '17 19:02

Petr


People also ask

How do HTTP requests and responses work?

The client—a web browser—sends an HTTP request to the server and receives a response. Both HTTP requests and responses begin with a sequence of header lines, each ending in a two-character sequence denoted as CRLF (carriage return-line feed, or " " in C strings).

What is web socket and how is it different from http?

What is web socket and how it is different from the HTTP? - GeeksforGeeks What is web socket and how it is different from the HTTP? HTTP and WebSocket both are communication protocols used in client-server communication. HTTP protocol: HTTP is unidirectional where the client sends the request and the server sends the response.

What's the next step after writing a request to a socket?

Assuming you've written the request to the socket, the next thing you'll want to do is: Read the response from the socket's input stream, parsing according to the HTTP spec.

How to receive response from custom HTTP server using TCP?

We will create a TCP socket. The default port is 80 for HTTP. But we will be using 8080 for running our test. You can use request module to receive response from custom HTTP server. A HTTP request consists of following. Request line: One line identifying the request type and path. Data: An optional data.


2 Answers

Firstly, you should know what http protocal and how it work.

and every http Request like:

  • Request Line
  • Request Header
  • Blank Line
  • Request Body.

and every http Response like:

  • Status Line
  • Response Header
  • Blank Line
  • Response Body.

However we can read the InputStream from http server, we can split every line we read from inputstream end with '/r/n'.

and your code:

while(true) {
    **line = in.readLine();**
    if  (line.indexOf("Content-Length") != -1)
    {
        len = Integer.parseInt( line.split("\\D+")[1] );
            //System.out.println("LINEE="+len);
        }

        out.println(line);
        str = str + line + '\n';
        if(line.isEmpty())  break;
    }
}

and in.readLine() return the every line not end with '/r/n', it return the line end with '/r' or '/n' . Maybe read from the inputstream block in here.

Here is a IOStreamUtils to read line end with '/r/n'.

https://github.com/mayubao/KuaiChuan/blob/master/app/src/main/java/io/github/mayubao/kuaichuan/micro_server/IOStreamUtils.java

like image 135
Ethan Avatar answered Oct 30 '22 23:10

Ethan


Try the following code:

// Get server response
int responseCode = connection.getResponseCode();
if (responseCode == 200) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String line;
    StringBuilder builder = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        builder.append(line);
    }
    String response = builder.toString()
    // Handle response...
}
like image 42
Eyal Biran Avatar answered Oct 30 '22 21:10

Eyal Biran