Topic
No replies
Venky Koneru
Venky Koneru
1 Post
ACCEPTED ANSWER

Pinned topic How to capture http request header using java proxy

‏2009-12-10T10:28:01Z |
I write a java proxy to intercept all the request from apache server to tomcat server. I need to capture all the request header to do some filtering and redirection.

I face an issue is BufferedInputStream don't know when the end of file. at the ending of file, it will keep waiting until the socket expired.

for all the incoming requests, i will assign it into a thread to handle all the request. In my code, first i will read line by line to get the header info. After header, i get input in byte and direct send to output stream.

My problem is:-
  • I can capture all the header information for first time request. But i cannot capture the header for second request if first socket not expired yet because it will using same socket. May i know how to capture all the header for all the incoming request?

below is my code:



while ((data = readLine(in)) != 

null) 
{ pos = data.toLowerCase().indexOf(
"host: "); 

if (pos == 0) 
{ host.setLength(0); host.append(data.substring(pos + 5).trim()); 
}   pos = data.toLowerCase().indexOf(
"cookie:"); 

if (pos == 0) 
{ cookie.setLength(0); cookie.append(data.substring(pos + 7).trim()); 
}   pos = data.toLowerCase().indexOf(
"get /"); 

if (pos == 0) 
{ url.setLength(0); url.append(data.substring(pos + 4).trim()); 
} data += 
"\r\n"; out.write(data.getBytes(), 0, data.length()); 
}   in.mark(1); 

if (in.read() == -1) 
{ 
} 

else 
{ in.reset(); 
} 

byte[] buf = 

new 

byte[50]; 

int bytesIn = 0; 

while (

true) 
{ bytesIn = in.read(buf);   

if (bytesIn == -1) 
{ in.close(); out.close(); 

break; 
} out.write(buf, 0, bytesIn); byteCount += bytesIn; 
}

readLine function:




protected String readLine(InputStream in) 

throws IOException 
{ 
// reads a line of text from an InputStream StringBuffer data = 

new StringBuffer(
""); 

int c;   

try 
{ 
// if we have nothing to read, just return null in.mark(1); 

if (in.read() == -1) 

return 

null; 

else in.reset();   

while ((c = in.read()) >= 0) 
{ 
// check for an end-of-line character 

if ((c == 0) || (c == 10) || (c == 13)) 

break; 

else data.append((

char) c); 
}   
// deal with the case where the end-of-line terminator is \r\n 

if (c == 13) 
{ in.mark(1); 

if (in.read() != 10) in.reset(); 
} 
} 

catch (Exception e) 
{   
}   
// and return what we have 

return data.toString(); 
}