Trying to create a proxy, doesn't work - java

I have an assignment to write a proxy server. Simple tests work, but when I configure firefox to use the proxy, the response input stream is never ready. Can you help?
ProxyServer (the important method)
public void start() {
while (true) {
Socket serverSocket;
Socket clientSocket;
BufferedWriter toClient;
BufferedWriter toServer;
try {
//The client is meant to put data on the port, read the socket.
clientSocket = listeningSocket.accept();
Request request = new Request(clientSocket.getInputStream());
System.out.println("Accepted a request!\n" + request);
while(request.busy);
//Make a connection to a real proxy.
//Host & Port - should be read from the request
URL url = null;
try {
url = new URL(request.getRequestURL());
} catch (MalformedURLException e){
url = new URL("http:\\"+request.getRequestHost()+request.getRequestURL());
}
//remove entry from cache if needed
if (!request.getCacheControl().equals(CacheControl.CACHE) && cache.containsRequest(request)) {
cache.remove(request);
}
Response response = null;
if (request.getRequestType() == RequestType.GET && request.getCacheControl().equals(CacheControl.CACHE) && cache.containsRequest(request)) {
response = cache.get(request);
} else {
//Get the response from the destination
int remotePort = (url.getPort() == -1) ? 80 : url.getPort();
System.out.println("I am going to try to connect to: " + url.getHost() + " at port " + remotePort);
serverSocket = new Socket(url.getHost(), remotePort);
System.out.println("Connected.");
//write to the server - keep it open.
System.out.println("Writing to the server's buffer...");
toServer = new BufferedWriter(new OutputStreamWriter(serverSocket.getOutputStream()));
toServer.write(request.getFullRequest());
toServer.flush();
System.out.println("flushed.");
System.out.println("Getting a response...");
response = new Response(serverSocket.getInputStream());
System.out.println("Got a response!\n" + response);
//wait for the response
while(response.isBusy());
}
if (request.getRequestType() == RequestType.GET && request.getCacheControl().equals(CacheControl.CACHE)) {
cache.put(request, response);
}
response = filter.filter(response);
// Return the response to the client
toClient = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
toClient.write(response.getFullResponse());
toClient.flush();
toClient.close();
} catch (IOException e) {
e.printStackTrace();
continue;
}
}
}
The Response and Request classes are just very simple parsers for HTTP requests/responses. When I try to load a website through the proxy, I get:
EDIT 2
Here's another attempt. I added a debug print just before the line toClient.write(response.getFullResponse());
Accepted a request!
Request
==============================
GET http://t2.technion.ac.il/~srachum/ HTTP/1.1
Host: t2.technion.ac.il
User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:2.0) Gecko/20100101 Firefox/4.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Proxy-Connection: keep-alive
I am going to try to connect to: t2.technion.ac.il at port 80
Connected.
Writing to the server's buffer...
flushed.
Getting a response...
Got a response!
Response
==============================
HTTP/1.1 200 OK
Date: Sat, 23 Apr 2011 15:54:08 GMT
Server: Apache/2.0.52 (Red Hat)
Last-Modified: Fri, 18 Mar 2011 23:45:24 GMT
ETag: "14928fc-877-49eca5f29cd00"
Accept-Ranges: bytes
Content-Length: 2167
Connection: close
Content-Type: text/html
X-Pad: avoid browser bug
<html>
...
</html>
I am going to write the following response:
HTTP/1.1 200 OK
Date: Sat, 23 Apr 2011 15:54:08 GMT
Server: Apache/2.0.52 (Red Hat)
Last-Modified: Fri, 18 Mar 2011 23:45:24 GMT
ETag: "14928fc-877-49eca5f29cd00"
Accept-Ranges: bytes
Content-Length: 2167
Connection: close
Content-Type: text/html
X-Pad: avoid browser bug
<html>
...
</html>
EDIT 3:
Request
package cs236369.proxy;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import cs236369.proxy.types.CacheControl;
import cs236369.proxy.types.HttpPatterns;
import cs236369.proxy.types.RequestHeader;
import cs236369.proxy.types.RequestType;
public class Request {
private String fullRequest = "";
private BufferedReader reader;
private RequestHeader requestHeader;
private String requestHost;
boolean busy = true;
private CacheControl cacheControl = CacheControl.CACHE;
public CacheControl getCacheControl() {
return cacheControl;
}
Request(String request) {
this(new ByteArrayInputStream(request.getBytes()));
}
Request(InputStream input){
reader = new BufferedReader(new InputStreamReader(input));
try {
while(!reader.ready()); //wait for initialization.
String line;
while ((line = reader.readLine()) != null) {
fullRequest += "\r\n" + line;
if (HttpPatterns.CACHE_CONTROL.matches(line)) {
cacheControl = (CacheControl) HttpPatterns.RESPONSE_CODE.process(line);
} else if (HttpPatterns.REQUEST_HEADER.matches(line)) {
requestHeader = (RequestHeader) HttpPatterns.REQUEST_HEADER.process(line);
} else if (HttpPatterns.HOST.matches(line)) {
requestHost = (String) HttpPatterns.HOST.process(line);
}
}
fullRequest = "\r\n" + fullRequest.trim() + "\r\n\r\n";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
busy = false;
}
public String getFullRequest() {
return fullRequest;
}
public RequestType getRequestType() {
return requestHeader.type;
}
public String getRequestURL() {
return requestHeader.url;
}
public String getRequestProtocol() {
return requestHeader.protocol;
}
public String getRequestHost() {
return requestHost;
}
public boolean isBusy() {
return busy;
}
#Override
public String toString() {
return "Request\n==============================\n" + fullRequest;
}
}
Response
package cs236369.proxy;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import cs236369.proxy.types.CacheControl;
import cs236369.proxy.types.HttpPatterns;
public class Response {
private String fullResponse = "";
private BufferedReader reader;
private boolean busy = true;
private int responseCode;
private CacheControl cacheControl;
public Response(String input) {
this(new ByteArrayInputStream(input.getBytes()));
}
public Response(InputStream input) {
reader = new BufferedReader(new InputStreamReader(input));
try {
while (!reader.ready());//wait for initialization.
String line;
while ((line = reader.readLine()) != null) {
fullResponse += "\r\n" + line;
if (HttpPatterns.RESPONSE_CODE.matches(line)) {
responseCode = (Integer) HttpPatterns.RESPONSE_CODE.process(line);
} else if (HttpPatterns.CACHE_CONTROL.matches(line)) {
cacheControl = (CacheControl) HttpPatterns.CACHE_CONTROL.process(line);
}
}
reader.close();
fullResponse = "\r\n" + fullResponse.trim() + "\r\n\r\n";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
busy = false;
}
public CacheControl getCacheControl() {
return cacheControl;
}
public String getFullResponse() {
return fullResponse;
}
public boolean isBusy() {
return busy;
}
public int getResponseCode() {
return responseCode;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((fullResponse == null) ? 0 : fullResponse.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Response))
return false;
Response other = (Response) obj;
if (fullResponse == null) {
if (other.fullResponse != null)
return false;
} else if (!fullResponse.equals(other.fullResponse))
return false;
return true;
}
#Override
public String toString() {
return "Response\n==============================\n" + fullResponse;
}
}

Once I was writing a program to send HTTP requests... My code was like this:
String host="www.google.com";
String request="GET / HTTP/1.0\r\nHost: "+host+"\r\nAccept-Encoding: gzip\r\n\r\n";
System.out.println(request);
Socket sock=new Socket(host,80);
InputStream inp=sock.getInputStream();
OutputStream outp=sock.getOutputStream();
outp.write(request.getBytes());
byte[] buff=new byte[999];
while(true){
int n=inp.read(buff);
if(n<0) break;
System.out.println(new String(buff,0,n));
}
inp.close();
outp.close();
sock.close();
This code works. At first sight, it looks like yours. You can try combining the two and watch when problems start to occur. Maybe there is something wrong in your Response parser?
P.S. Are you sure that the original request you got from the browser ends with two line breaks? In the log you posted it seems that there is only one blank line...
EDIT: I compiled your code with minor modifications, and it works fine. The things I did:
Commented out everything about CacheControl, filtering and RequestHeader because I don't have sources for these classes;
Added simple parsing of URL and host because it won't work without them;
Added a check to remove Accept-Encoding because many servers use gzip which gets corrupted in this program;
Added a check to stop parsing the request after two line breaks.
This program serves as a proxy server for Firefox and works fine with HTML code. Please compile my version and try whether it works for you. Probably there is something to do with Firefox settings?
Please note that this proxy server is corrupting binary data such as images and gzipped HTML. This must be caused by the usage of InputStreamReader and OutputStreamWriter; they convert bytes to characters and vice versa, this is good for text but for binary data you'd better use InputStream and OutputStream "as is".
public class AmirRachum {
public static void main(String[] args) {
try{
int port=38824;
ServerSocket listeningSocket=new ServerSocket(port);
System.out.println("Socket created");
while (true) {
Socket serverSocket;
Socket clientSocket;
BufferedWriter toClient;
BufferedWriter toServer;
try {
//The client is meant to put data on the port, read the socket.
clientSocket = listeningSocket.accept();
Request request = new Request(clientSocket.getInputStream());
System.out.println("Accepted a request!\n" + request);
while(request.busy);
//Make a connection to a real proxy.
//Host & Port - should be read from the request
URL url = null;
try {
url = new URL(request.getRequestURL());
} catch (MalformedURLException e){
url = new URL("http:\\"+request.getRequestHost()+request.getRequestURL());
}
//remove entry from cache if needed
/* if (!request.getCacheControl().equals(CacheControl.CACHE) && cache.containsRequest(request)) {
cache.remove(request);
}*/
Response response = null;
/* if (request.getRequestType() == RequestType.GET && request.getCacheControl().equals(CacheControl.CACHE) && cache.containsRequest(request)) {
response = cache.get(request);
} else*/ {
//Get the response from the destination
int remotePort = (url.getPort() == -1) ? 80 : url.getPort();
System.out.println("I am going to try to connect to: " + url.getHost() + " at port " + remotePort);
serverSocket = new Socket(url.getHost(), remotePort);
System.out.println("Connected.");
//write to the server - keep it open.
System.out.println("Writing to the server's buffer...");
toServer = new BufferedWriter(new OutputStreamWriter(serverSocket.getOutputStream()));
toServer.write(request.getFullRequest());
toServer.flush();
System.out.println("flushed.");
System.out.println("Getting a response...");
response = new Response(serverSocket.getInputStream());
System.out.println("Got a response!\n" + response);
//wait for the response
while(response.isBusy());
}
/* if (request.getRequestType() == RequestType.GET && request.getCacheControl().equals(CacheControl.CACHE)) {
cache.put(request, response);
}
response = filter.filter(response);*/
// Return the response to the client
toClient = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
toClient.write(response.getFullResponse());
toClient.flush();
toClient.close();
} catch (IOException e) {
e.printStackTrace();
continue;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static class Request {
private String fullRequest = "";
private BufferedReader reader;
// private RequestHeader requestHeader;
private String requestHost;
private String requestURL;
boolean busy = true;
// private CacheControl cacheControl = CacheControl.CACHE;
/* public CacheControl getCacheControl() {
return cacheControl;
}*/
Request(String request) {
this(new ByteArrayInputStream(request.getBytes()));
}
Request(InputStream input){
reader = new BufferedReader(new InputStreamReader(input));
try {
while(!reader.ready()); //wait for initialization.
String line;
while ((line = reader.readLine()) != null) {
if(!line.startsWith("Accept-Encoding:")) fullRequest += "\r\n" + line;
/* if (HttpPatterns.CACHE_CONTROL.matches(line)) {
cacheControl = (CacheControl) HttpPatterns.RESPONSE_CODE.process(line);
} else if (HttpPatterns.REQUEST_HEADER.matches(line)) {
requestHeader = (RequestHeader) HttpPatterns.REQUEST_HEADER.process(line);
} else if (HttpPatterns.HOST.matches(line)) {
requestHost = (String) HttpPatterns.HOST.process(line);
}*/
if(line.startsWith("GET ")){requestURL=line.split(" ")[1];System.out.println("url \""+requestURL+"\"");}
if(line.startsWith("Host:")){requestHost=line.substring(6);System.out.println("Host \""+requestHost+"\"");}
if(line.length()==0){System.out.println("empty line");break;}
}
fullRequest = "\r\n" + fullRequest.trim() + "\r\n\r\n";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
busy = false;
}
public String getFullRequest() {
return fullRequest;
}
/* public RequestType getRequestType() {
return requestHeader.type;
}*/
public String getRequestURL() {
return requestURL;
}
/* public String getRequestProtocol() {
return requestHeader.protocol;
}*/
public String getRequestHost() {
return requestHost;
}
public boolean isBusy() {
return busy;
}
//#Override
public String toString() {
return "Request\n==============================\n" + fullRequest;
}
}
public static class Response {
private String fullResponse = "";
private BufferedReader reader;
private boolean busy = true;
// private int responseCode;
// private CacheControl cacheControl;
public Response(String input) {
this(new ByteArrayInputStream(input.getBytes()));
}
public Response(InputStream input) {
reader = new BufferedReader(new InputStreamReader(input));
try {
while (!reader.ready());//wait for initialization.
String line;
while ((line = reader.readLine()) != null) {
fullResponse += "\r\n" + line;
/* if (HttpPatterns.RESPONSE_CODE.matches(line)) {
responseCode = (Integer) HttpPatterns.RESPONSE_CODE.process(line);
}/* else if (HttpPatterns.CACHE_CONTROL.matches(line)) {
cacheControl = (CacheControl) HttpPatterns.CACHE_CONTROL.process(line);
}*/
}
reader.close();
fullResponse = "\r\n" + fullResponse.trim() + "\r\n\r\n";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
busy = false;
}
/* public CacheControl getCacheControl() {
return cacheControl;
}*/
public String getFullResponse() {
return fullResponse;
}
public boolean isBusy() {
return busy;
}
/* public int getResponseCode() {
return responseCode;
}*/
//#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((fullResponse == null) ? 0 : fullResponse.hashCode());
return result;
}
//#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Response))
return false;
Response other = (Response) obj;
if (fullResponse == null) {
if (other.fullResponse != null)
return false;
} else if (!fullResponse.equals(other.fullResponse))
return false;
return true;
}
//#Override
public String toString() {
return "Response\n==============================\n" + fullResponse;
}
}
}

Related

Java reading from a server on port returns -1

I have to write a socket program to communicate with a server on a given port and DNS. The communication can be a single message or a list of messages; against every message a response is generated from the server. Once a connection is made I receive a response for the first message, but on the next message receive a response of -1. The following is the class handling client server communication:
public class SocketCommunication {
static String[] adresses = null;
final static int port = 1234;
final static int timeout = 60000;
static long pbmId;
private static int count = 0;
private static void loadPBMDNS()
{
DynamicQuery pbmQuery = PH_PBM_SwitchLocalServiceUtil.dynamicQuery();
pbmQuery.add(RestrictionsFactoryUtil.eq("Activated", true));
try
{
List<PH_PBM_Switch> pbmList = PH_PBM_SwitchLocalServiceUtil.dynamicQuery(pbmQuery);
if(pbmList != null && pbmList.size() > 0)
{
if(pbmList.get(0).getServer_DNS() != null
&& !pbmList.get(0).getServer_DNS().equals(""))
{
pbmId = pbmList.get(0).getPBM_Switch_Id();
if(pbmList.get(0).getServer_DNS().contains(";"))
{
String[] tokens = pbmList.get(0).getServer_DNS().split(";");
System.out.println(tokens.toString());
adresses = tokens;
}
else
{
adresses[0] = pbmList.get(0).getServer_DNS();
}
}
}
}
catch (SystemException e)
{
e.printStackTrace();
}
}
public static ArrayList<BatchClaimVO> ConnectSendAndReadResponse
(int addressNumber, ArrayList<BatchClaimVO> batchClaimVOs)
{
try
{
loadPBMDNS();
System.out.println("Connecting to " + adresses[addressNumber] + " on port " + port);
SocketFactory sslsocketfactory = SSLSocketFactory.getDefault();
SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket();
sslsocket.connect(new InetSocketAddress(adresses[addressNumber], port), timeout);
System.out.println("Just connected to " + sslsocket.getRemoteSocketAddress());
for (int i = count; i < batchClaimVOs.size(); i++)
{
sendClaim(
sslsocket,
batchClaimVOs.get(i).getCb(),
batchClaimVOs.get(i).getUniqueIdentifier()
);
if(addressNumber <= 2)
{
batchClaimVOs.get(i).setResponse
(readResponse(sslsocket, addressNumber, batchClaimVOs.get(i).getCb()));
}
}
System.out.println("Closing socket");
count = 0;
sslsocket.close();
return batchClaimVOs;
}
catch (IOException e)
{
if(addressNumber < 2)
{
System.out.println("connection timedout trying again on new DNS");
ConnectSendAndReadResponse(++addressNumber, batchClaimVOs);
}
else
{
System.out.println
("unable to connect to server or server did not responed intime");
e.printStackTrace();
}
}
return null;
}
public static void sendClaim(SSLSocket sslSocket, ClaimBuilder cb, long uniqueIdentifier)
throws IOException
{
System.out.println("sending claim");
OutputStream outToServer = sslSocket.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeBytes(cb.getClaim());
System.out.println("claim sent");
SaveRequestLog(uniqueIdentifier, cb.getClaim(), pbmId);
}
public static void SaveRequestLog(long uniqueIdentifier, String claim, long pbmId)
{
if(uniqueIdentifier > 0)
{
try
{
PH_Request_Transaction_Log log = PH_Request_Transaction_LogLocalServiceUtil.getPH_Request_Transaction_Log(uniqueIdentifier);
log.setPBM_Switch_Id(pbmId);
log.setRequest_Log(claim);
log.setCreated_By(LiferayFacesContext.getInstance().getUserId());
log.setCreated_Date(Calendar.getInstance().getTime());
PH_Request_Transaction_LogLocalServiceUtil.updatePH_Request_Transaction_Log(log);
}
catch (PortalException e)
{
e.printStackTrace();
}
catch (SystemException e)
{
e.printStackTrace();
}
}
}
public static String readResponse(SSLSocket sslSocket, int addressNumber, ClaimBuilder cb)
throws IOException
{
sslSocket.setSoTimeout(timeout);
InputStream inFromServer = sslSocket.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
byte[] data = new byte[1048];
int count = in.read(data);
System.out.println(count);
System.out.println(new String(data));
String response = fixString(new String(data), count);
System.out.println("Verifying checksum");
if(verifyTransmissionCheckSum(response))
{
System.out.println("checksum verified");
System.out.println(response);
}
else
{
System.out.println("transmission corrupted");
}
sendAcknowledgement(sslSocket, cb);
return response;
}
public static void sendAcknowledgement(SSLSocket sslSocket, ClaimBuilder cb)
throws IOException
{
System.out.println("sending Acknowledgement");
OutputStream outToServer = sslSocket.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeBytes(cb.buildClaimAcknowledgement());
System.out.println("Acknowledgement Sent");
count++;
}
public static String fixString(String toFix, int count)
{
return toFix.substring(0, count);
}
public static boolean verifyTransmissionCheckSum(String str)
{
return (Integer.parseInt((String) str.subSequence(0, 4))
== (str.subSequence(4, str.length())).length())
? true : false;
}
}
The given server do not support batch communication.

SOAP request body (XML) in HTTPServletRequest always empty (JAVA)

I know a similar problem has been posted several times on StackOverflow, still all the answers did not help in my case.
Target: I need to log the SOAP-Request XML into a database before processing it further.
For this discussion, I'm happy if I can get it as a String and log it to console.
Problem: Request XML is always empty.
Environment: IBM WebSphere Application Server v8.5, EJB 3.1 web service (session bean)
I actually produced a working solution using javax.xml.soap.SOAPBody and SOAPMessage, but on production there seems to be another component which causes the following JAX-WS conflict:
ERROR org.apache.axis2.engine.AxisEngine receive - com.sun.xml.messaging.saaj.soap.ver1_1.Body1_1Impl incompatible with com.ibm.ws.webservices.engine.xmlsoap.SOAPBody
Yes, there are multiple workarounds on StackOverflow and IBM about changing the ClassLoader policy, like "local class loader first (parent last)", but we currently can't go this way.
So, my current approach (which was working on a different servlet) is to get the HTTPServletRequest, get it's InputStream and convert it to a String using IOUtils.toString().
I am aware that a request can only be consumed once and I found several approaches to avoid it (like using a HTTPServletRequestWrapper) but even using these workarounds the request XML is always empty.
Eventually I want to do the logging in an adapter, but for testing reasons I also put my attempts into the service itself (it did not have any effect).
The strange thing is: I can read all Headers and Attributes from the request (using request.getHeader() and request.getAttribute()! Only the body itself is blank!
I'm testing the application using SoapUI.
Request-XML:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ping="http://services.axonactive.com/wsdl/cet/pingservice-v1.0">
<soapenv:Header/>
<soapenv:Body>
<ping:PingPingIn/>
</soapenv:Body>
</soapenv:Envelope>
Response is actually irrelevant, but correctly working.
Console output:
[ch.zek.ecls.EclsPingServiceImpl]: Initialization successful.
EclsPingServiceImpl ping - start ping()...
EclsPingServiceImpl ping - Body:
EclsPingServiceImpl ping - body2:
EclsUtil printRequestData - [H] Accept-Encoding: gzip,deflate
EclsUtil printRequestData - [H] Content-Type: text/xml;charset=UTF-8
EclsUtil printRequestData - [H] SOAPAction: ""
EclsUtil printRequestData - [H] Content-Length: 254
EclsUtil printRequestData - [H] Host: localhost:9443
EclsUtil printRequestData - [H] Connection: Keep-Alive
EclsUtil printRequestData - [H] User-Agent: Apache-HttpClient/4.1.1 (java 1.5)
EclsUtil printRequestData - [A] javax.servlet.request.key_size: 128
EclsUtil printRequestData - [A] javax.servlet.request.cipher_suite: SSL_RSA_WITH_AES_128_CBC_SHA
EclsUtil printRequestData - [A] com.ibm.websphere.servlet.uri_non_decoded: /NewZekEclsHTTPRouter/PingService
EclsPingServiceImpl ping - end ping()
Edit: Note the headers [H] for Content-Type and Content-Length:
They "know" the content - if I put some more characters into the request XML then Content-Length is updated accordingly.
So I conclude that the content is not lost, but somehow not accessible... .
Webservice:
public class EclsPingServiceImpl{
#javax.annotation.Resource
WebServiceContext wsContext;
#javax.annotation.Resource
SessionContext sessionContext;
private Log log = LogFactory.getLog(EclsPingServiceImpl.class);
public PingOut ping(PingIn parameters) throws PingEntityNotFoundException, PingPermissionException, PingSystemException {
MessageContext messageContext = wsContext.getMessageContext();
HttpServletRequest request = (HttpServletRequest) messageContext.get(MessageContext.SERVLET_REQUEST);
// start Try 1
MultiReadHttpServletRequest multiReadHttpServletRequest = new MultiReadHttpServletRequest(request);
try {
InputStream bodyInputStream = multiReadHttpServletRequest.getInputStream();
String body = IOUtils.toString(bodyInputStream);
if (log.isDebugEnabled()) {
log.debug("Body: " + body);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// end Try 1
// start Try 2
try {
InputStream body2 = request.getInputStream();
String xml = IOUtils.toString(body2, "UTF-8");
if (log.isDebugEnabled()) {
log.debug("body2: " + xml);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// end Try 2
// Get Header data:
Enumeration<String> headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
if (log.isDebugEnabled()) {
log.debug("[H] " + headerName + ": " + request.getHeader(headerName));
}
}
// Get Attribute data:
Enumeration<String> attributeNames = request.getAttributeNames();
while(attributeNames.hasMoreElements()) {
String attributeName = attributeNames.nextElement();
if (log.isDebugEnabled()) {
log.debug("[A] " + attributeName + ": " + request.getAttribute(attributeName));
}
}
PingOut pingOut = new PingOut();
// some irrelevant stuff...
return pingOut;
}
}
MultiReadHttpServletRequestWrapper:
Copied from StackOverflow: Http Servlet request lose params from POST body after read it once
public class MultiReadHttpServletRequest extends HttpServletRequestWrapper {
private ByteArrayOutputStream cachedBytes;
public MultiReadHttpServletRequest(HttpServletRequest request) {
super(request);
}
#Override
public ServletInputStream getInputStream() throws IOException {
if (cachedBytes == null)
cacheInputStream();
return new CachedServletInputStream();
}
#Override
public BufferedReader getReader() throws IOException{
return new BufferedReader(new InputStreamReader(getInputStream()));
}
private void cacheInputStream() throws IOException {
/* Cache the inputstream in order to read it multiple times. For
* convenience, I use apache.commons IOUtils
*/
cachedBytes = new ByteArrayOutputStream();
IOUtils.copy(super.getInputStream(), cachedBytes);
}
/* An inputstream which reads the cached request body */
public class CachedServletInputStream extends ServletInputStream {
private ByteArrayInputStream input;
public CachedServletInputStream() {
/* create a new input stream from the cached request body */
input = new ByteArrayInputStream(cachedBytes.toByteArray());
}
#Override
public int read() throws IOException {
return input.read();
}
}
}
LogHandler - just to show what I tried, too...:
public class EclsSimpleLogHandler implements javax.xml.ws.handler.soap.SOAPHandler
{
private Log log = LogFactory.getLog(EclsSimpleLogHandler.class);
#Override
public boolean handleMessage(MessageContext context) {
boolean success = false;
if (log.isDebugEnabled()) {
log.debug("handleMessage()...");
}
Boolean outboundProperty = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
// check if handler is called for inbound (request) or outbound (response) message
if (outboundProperty.booleanValue()) {
success = handleResponse(context);
} else {
//success = handleRequest(context);
success = true;
}
return success;
}
private boolean handleRequest(MessageContext messageContext) {
if(log.isDebugEnabled()) {
log.debug("handling request (inbound)");
}
// Initially logging planned here, moved out for testing reasons
boolean success = false;
return success;
}
private boolean handleResponse(MessageContext messageContext) {
if(log.isDebugEnabled()) {
log.debug("handling response (outbound)");
}
boolean success = false;
ByteArrayOutputStream outputStream = null;
SOAPMessageContext context = (SOAPMessageContext) messageContext;
SOAPMessage soapMessage = (SOAPMessage) context.getMessage();
try {
/*
Initial solution, but sometimes causing:
ERROR org.apache.axis2.engine.AxisEngine receive - com.sun.xml.messaging.saaj.soap.ver1_1.Body1_1Impl
incompatible with com.ibm.ws.webservices.engine.xmlsoap.SOAPBody
// SOAPBody soapBody = soapMessage.getSOAPBody();
// String soapBodyXml = soapBody.toString();
*/
// This is working - but I want to avoid using SOAPMessage:
outputStream = new ByteArrayOutputStream();
soapMessage.writeTo(outputStream);
String soapBodyXml = new String(outputStream.toByteArray(), "UTF-8");
if (log.isDebugEnabled()) {
log.debug("responseXml:\n" + soapBodyXml);
}
success = true;
} catch (SOAPException e) {
if (log.isErrorEnabled()) {
log.error("Error while accessing SOAPMessage: " + e.getMessage());
}
} catch (IOException e) {
if (log.isErrorEnabled()) {
log.error("IOException for soapMessage.writeTo(): " + e.getMessage());
}
e.printStackTrace();
}
return success;
}
// Another method, but also resulting in an empty body:
static String extractPostRequestBody(HttpServletRequest request) {
if ("POST".equalsIgnoreCase(request.getMethod())) {
Scanner s = null;
try {
s = new Scanner(request.getInputStream(), "UTF-8").useDelimiter("\\A");
} catch (IOException e) {
e.printStackTrace();
}
return s.hasNext() ? s.next() : "";
}
return "";
}
// Another method, but also resulting in an empty body:
private String getRequestBody(HttpServletRequest request) {
HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper(request);
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null;
try {
InputStream inputStream = requestWrapper.getInputStream();
if (inputStream != null) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
char[] charBuffer = new char[128];
int bytesRead = -1;
while ((bytesRead = bufferedReader.read(charBuffer)) != -1) {
stringBuilder.append(charBuffer, 0, bytesRead);
}
}
} catch (IOException ex) {
log.error("Error reading the request payload", ex);
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException iox) {
// ignore
}
}
}
return stringBuilder.toString();
}
}

Java TCP Simple Webserver Problems with response codes (homework)

This is an assignment for a course we are having and i need some help.
I am having problems for example, trying to request a file that does not exist, it works that a 404 file not found page comes up, but when i look in the web tool for Safari i can see that the response code is 200, OK, which is definialty wrong, it should be the code that is the error.
But why i don't see, i send the error code header when a error occurs, but it´still doesn't work. Can somebody point me at the right direction or maybe just say what the problem is and i can fix it :D ?
Main:
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
public class WebServer {
private static int PORT = 8888;
private static String ROOT_DIR = "";
public static void main(String[] args) {
if (isCorrect(args) == true) {
boolean isRunning = true;
try {
/* Creates a new server socket */
ServerSocket serverSocket = new ServerSocket();
/* Binds the port to the server */
SocketAddress localBindPoint = new InetSocketAddress(PORT);
serverSocket.bind(localBindPoint);
System.out.println("==============================================" +
"\n| HTTP Web Server |" +
"\n===================" +
"\n| Configuration: " +
"\n| Directory: " +
"\n| " + ROOT_DIR +
"\n| Port: " +
"\n| " + PORT +
"\n| Usage: <directory> <port>" +
"\n| ctrl-c to exit" +
"\n==============================================");
/* The server is running */
while (isRunning) {
try {
/* Accept connection by client */
Socket socket = serverSocket.accept();
/* Each connected client gets a new thread */
new Thread(new RequestHandler(socket, ROOT_DIR)).start();
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
} catch (IOException e) {
System.err.println("Address already in use!" +
"\nClose running connection or choose other port");
}
} else
usageMsg();
System.exit(1);
}
public static boolean isDirectory(String path){
File filePath = null;
try{
filePath = new File(path);
/* False if file is not a directory */
if (!filePath.isDirectory())
return false;
}
catch (Exception e){
System.err.println(e.getMessage());
}
/* Seems to be a file path */
return true;
}
public static boolean isCorrect(String[] args){
if (args.length != 2){
usageMsg();
return false;
}
try{
ROOT_DIR = args[0].toString();
PORT = Integer.parseInt(args[1]);
}
catch (NumberFormatException n){
System.err.println(n.getMessage());
}
if (!isDirectory(ROOT_DIR)){
usageMsg();
return false;
}
return true;
}
public static void usageMsg(){
System.err.println("Invalid arguments"+
"\nUsage: java -jar Webserver.jar <directory> <port>");
}
}
RequestHandler:
import java.io.*;
import java.net.Socket;
import java.util.StringTokenizer;
/**
* Web Server Request Handler.
* Created on 2015-02-16.
*/
public class RequestHandler implements Runnable {
/*
TODO ( ) Problem 1
TODO ( ) Problem 2
TODO ( ) Problem 3
TODO (X) Index page for first page.
TODO (X) Read and download images & other files
TODO ( ) Fix header responses
TODO ( ) Error responses
*/
private String
OK = "HTTP/1.0 200 OK",
NOT_FOUND = "HTTP/1.0 404 Not Found",
BAD_REQUEST = "HTTP/1.0 400 Bad Request",
FORBIDDEN = "HTTP/1.0 403 Forbidden",
SERVER_ERROR = "HTTP/1.0 500 Internal Server Error";
private String ROOT_DIR;
private Socket client;
private PrintStream send;
private DataInputStream fromClient;
private DataOutputStream out;
RequestHandler(Socket client, String ROOT_DIR) {
this.client = client;
this.ROOT_DIR = ROOT_DIR;
try {
send = new PrintStream(client.getOutputStream());
fromClient = new DataInputStream(client.getInputStream());
out = new DataOutputStream(new BufferedOutputStream(client.getOutputStream()));
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
/* Reads the HTTP request and responds */
public void run() {
String request = null;
String fileName = null;
StringTokenizer tok = null;
try {
/* Read HTTP request from client */
while ((request = fromClient.readLine()) != null) {
System.out.println(request);
tok = new StringTokenizer(request);
/* Extracts the file path from the GET command */
if (tok.hasMoreElements() && tok.nextToken().equals("GET")
&& tok.hasMoreElements()) {
fileName = tok.nextToken();
} else
throw new FileNotFoundException();
/* */
if (fileName.endsWith("/"))
fileName += "index.html";
/* Illegal characters, prevent access to super directories */
if (fileName.indexOf("..") >= 0 || fileName.indexOf('|') >= 0
|| fileName.indexOf(':') >= 0 || fileName.indexOf('~') >= 0) {
error(FORBIDDEN, "Forbidden Access", fileName);
}
else
if (new File(fileName).isDirectory()) {
fileName = fileName.replace('\\', '/');
send.close();
return;
}
/* File name is ROOT_DIR + file name */
fileName = ROOT_DIR + fileName;
/* Create file */
File file = new File(fileName);
if (file.isDirectory()) {
fileName = fileName + "index.html";
}
/* File does not exist */
if (file.exists()){
/* Determines the MIME type of the file */
String mimeType = getMimeType(file);
/* Sends the file */
sendFile(file, mimeType, fileName);
client.close();
}
else
error(NOT_FOUND, "404 File Not Found", fileName);
}
}
catch (FileNotFoundException e) {
System.err.println(e.getMessage());
}
catch (IOException e){
System.err.println(e.getMessage());
}
}
/* Sends the requested file to the client */
public void sendFile(File file, String fileType, String fileName) {
try {
// Buffer must not be to low, => fragments
int length = (int) file.length();
FileInputStream fileIn = new FileInputStream(fileName);
byte[] bytes = new byte[length];
/* Write until bytes is empty */
while ((length = fileIn.read(bytes)) != -1 ){
out.write(bytes, 0, length);
out.flush();
out.writeBytes(OK);
out.writeBytes("Server: Jakobs Web Server v1.0");
out.writeBytes("Content-Type: " + fileType + "\r\n");
out.writeBytes("Content-Length: " + length + "\r\n");
out.writeBytes("");
}
send.close();
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
/* Sends the header response to the client */
public void sendHeaderResponse(String code, String fileType){
try {
out.writeBytes(code);
out.writeBytes("Server: Jakobs Web Server v1.0");
out.writeBytes("Content-Type: " + fileType + "\r\n");
out.writeBytes("");
}
catch (IOException e){
System.err.println(e.getMessage());
}
}
/* Sends error response to the client */
public void error(String code, String error, String fileName){
System.err.println(error +
"\nFile Requested: " + fileName);
/* Sends the error code header */
sendHeaderResponse(code, fileName);
/* Sends the error message and cause to client */
send.print("<html><head><title>" + error + "</title></head><body>");
send.print("<h1>" + error + "</h1>\r\n");
send.println("Location: /" + fileName + "/\r\n");
send.println("Exception Cause: " + error + "\r\n");
send.print("Start Page");
send.print("</body>\"</html>");
send.flush();
send.close();
}
/* Finds out the MIME type of the requested file */
public String getMimeType(File f) {
String file = f.toString();
String type = "";
if (file.endsWith(".txt")) {
type = "text/txt";
} else if (file.endsWith(".html") || file.endsWith("htm")) {
type = "text/html";
} else if (file.endsWith(".jpg")) {
type = "image/jpg";
} else if (file.endsWith(".png")) {
type = "image/png";
} else if (file.endsWith(".jpeg")) {
type = "image/jpeg";
} else if (file.endsWith(".gif")) {
type = "image/gif";
} else if (file.endsWith(".pdf")) {
type = "application/pdf";
} else if (file.endsWith(".mp3")) {
type = "audio/mpeg";
} else if (file.endsWith(".class")){
type = "application/octet-stream";
} else if (file.endsWith(".mp4")){
type = "video/mp4";
}
return type;
}
}
Make sure that you write e.g. HTTP/1.1 404 Not Found to the client, not just the 400.
Actually no, your problem is that you don't end the response properly. The browser keeps receiving data and shows no response code received. Let me see how this can be fixed in your code.
Also, you use two wrapper streams around client.getOutputStream() to send data to the client (send and out). Not sure why you do this. This looks weird. You should use just one wrapper stream. And you never close out, probably that's your problem, that's why the browser thinks the response is not yet fully received. Try to use one stream and handle it properly.
OK, here is your code fixed.
import java.io.*;
import java.net.Socket;
import java.util.StringTokenizer;
/**
* Web Server Request Handler.
* Created on 2015-02-16.
*/
public class RequestHandler implements Runnable {
/*
TODO ( ) Problem 1
TODO ( ) Problem 2
TODO ( ) Problem 3
TODO (X) Index page for first page.
TODO (X) Read and download images & other files
TODO ( ) Fix header responses
TODO ( ) Error responses
*/
private String
OK = "HTTP/1.0 200 OK",
NOT_FOUND = "HTTP/1.0 404 Not Found",
BAD_REQUEST = "HTTP/1.0 400 Bad Request",
FORBIDDEN = "HTTP/1.0 403 Forbidden",
SERVER_ERROR = "HTTP/1.0 500 Internal Server Error";
private String ROOT_DIR;
private Socket client;
private PrintStream send;
private DataInputStream fromClient;
// private DataOutputStream out;
RequestHandler(Socket client, String ROOT_DIR) {
this.client = client;
this.ROOT_DIR = ROOT_DIR;
try {
send = new PrintStream(client.getOutputStream());
fromClient = new DataInputStream(client.getInputStream());
// out = new DataOutputStream(new BufferedOutputStream(client.getOutputStream()));
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
/* Reads the HTTP request and responds */
public void run() {
String request = null;
String fileName = null;
StringTokenizer tok = null;
try {
/* Read HTTP request from client */
while ((request = fromClient.readLine()) != null) {
System.out.println(request);
tok = new StringTokenizer(request);
/* Extracts the file path from the GET command */
if (tok.hasMoreElements() && tok.nextToken().equals("GET")
&& tok.hasMoreElements()) {
fileName = tok.nextToken();
} else
throw new FileNotFoundException();
/* */
if (fileName.endsWith("/"))
fileName += "index.html";
/* Illegal characters, prevent access to super directories */
if (fileName.indexOf("..") >= 0 || fileName.indexOf('|') >= 0
|| fileName.indexOf(':') >= 0 || fileName.indexOf('~') >= 0) {
error(FORBIDDEN, "Forbidden Access", fileName);
}
else
if (new File(fileName).isDirectory()) {
fileName = fileName.replace('\\', '/');
send.close();
return;
}
/* File name is ROOT_DIR + file name */
fileName = ROOT_DIR + fileName;
/* Create file */
File file = new File(fileName);
if (file.isDirectory()) {
fileName = fileName + "index.html";
}
/* File does not exist */
if (file.exists()){
/* Determines the MIME type of the file */
String mimeType = getMimeType(file);
/* Sends the file */
sendFile(file, mimeType, fileName);
client.close();
}
else
error(NOT_FOUND, "404 File Not Found", fileName);
}
}
catch (FileNotFoundException e) {
System.err.println(e.getMessage());
}
catch (IOException e){
System.err.println(e.getMessage());
}
}
/* Sends the requested file to the client */
public void sendFile(File file, String fileType, String fileName) {
try {
// Buffer must not be to low, => fragments
int length = 0; // (int) file.length();
FileInputStream fileIn = new FileInputStream(fileName);
byte[] bytes = new byte[1024];
ByteArrayOutputStream bos = new ByteArrayOutputStream();
/* Write until bytes is empty */
while ((length = fileIn.read(bytes)) != -1 ){
bos.write(bytes, 0, length);
// send.write(bytes, 0, length);
// send.flush();
}
bos.flush();
bos.close();
byte[] data1 = bos.toByteArray();
System.out.print(new String(data1));
send.print(OK);
send.print("");
send.print("Server: Jakobs Web Server v1.0");
send.print("Content-Type: " + fileType + "\r\n");
send.print("Content-Length: " + data1.length + "\r\n");
send.println("");
send.write(data1, 0, data1.length);
send.println("");
send.flush();
send.close();
fileIn.close();
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
/* Sends the header response to the client */
public void sendHeaderResponse(String code, String fileType){
try {
send.print(code);
send.print("Server: Jakobs Web Server v1.0");
send.print("Content-Type: " + fileType + "\r\n");
send.print("");
send.println();
}
catch (Exception e){
System.err.println(e.getMessage());
}
}
/* Sends error response to the client */
public void error(String code, String error, String fileName){
System.err.println(error +
"\nFile Requested: " + fileName);
/* Sends the error code header */
sendHeaderResponse(code, fileName);
// send.println("ERROR");
/* Sends the error message and cause to client */
send.print("<html><head><title>" + error + "</title></head><body>");
send.print("<h1>" + error + "</h1>\r\n");
send.println("Location: /" + fileName + "/\r\n");
send.println("Exception Cause: " + error + "\r\n");
send.print("Start Page");
send.print("</body></html>");
send.flush();
send.close();
}
/* Finds out the MIME type of the requested file */
public String getMimeType(File f) {
String file = f.toString();
String type = "";
if (file.endsWith(".txt")) {
type = "text/txt";
} else if (file.endsWith(".html") || file.endsWith("htm")) {
type = "text/html";
} else if (file.endsWith(".jpg")) {
type = "image/jpg";
} else if (file.endsWith(".png")) {
type = "image/png";
} else if (file.endsWith(".jpeg")) {
type = "image/jpeg";
} else if (file.endsWith(".gif")) {
type = "image/gif";
} else if (file.endsWith(".pdf")) {
type = "application/pdf";
} else if (file.endsWith(".mp3")) {
type = "audio/mpeg";
} else if (file.endsWith(".class")){
type = "application/octet-stream";
} else if (file.endsWith(".mp4")){
type = "video/mp4";
}
return type;
}
}

service called two times

I am trying to call my HttpServer with a POST and send a message in the body, on the server side I can see that it is called twice and I cannot figure out why.
Here is a part of the client code
String URL = "http://localhost:8081/" + path +"/service?session=" + sessionId;
connection = openConnection(URL, "POST");
OutputStream output = connection.getOutputStream();
output.write("Some Random body data".getBytes());
output.close();
stream = connection.getInputStream();
stream.close();
connection.disconnect();
On the server side i can see that the service is called two times. I figure it has to do something with my OutputStream and InputStream, but if i dont call the input stream it wont call the service any time.
EDIT!!!
Here is some more code
public class Server {
private static final int BASE_PORT = 8081;
public static void main(String[] args) {
try{
InetSocketAddress address = new InetSocketAddress(BASE_PORT);
HttpServer server = HttpServer.create(address, 0);
server.createContext("/", new PathDelegator());
server.setExecutor(Executors.newCachedThreadPool());
server.start();
System.out.println("Server is listening on : " + BASE_PORT);
}catch(IOException e){
e.printStackTrace();
}
}
}
public class PathDelegator implements HttpHandler{
public void handle(HttpExchange exchange) throws IOException {
String URI = exchange.getRequestURI().toString();
if(URI.indexOf("/session") != -1){
//Call ServiceHandler
System.out.println("Call ServiceHandler");
serviceHandler(exchange, "some session key");
}
}
private void serviceHandler(HttpExchange exchange, String sessionId) throws IOException{
String requestMethod = exchange.getRequestMethod();
OutputStream responseBody = exchange.getResponseBody();
if(requestMethod.equalsIgnoreCase("POST")){
Headers responseHeaders = exchange.getResponseHeaders();
responseHeaders.set("Content-Type", "text/plain");
InputStream stream = exchange.getRequestBody();
int b = 0;
StringBuffer buffer = new StringBuffer();
while((b = stream.read()) != -1){
buffer.append((char)b);
}
System.out.println("body data: " + buffer.toString());
exchange.sendResponseHeaders(200, 0);
}else {
exchange.sendResponseHeaders(400, 0);
}
responseBody.close();
}
}
public class ClientTest {
#Test
public void shouldBeAbleToPostToService(){
try {
String SCORE_URL = "http://localhost:8081/service?session=" + sessionId;
connection = openConnection(URL, "POST");
OutputStream output = connection.getOutputStream();
output.write("Some body data".getBytes());
output.close();
stream = connection.getInputStream();
stream.close();
connection.disconnect();
fail("Not implemented yet!");
} catch (IOException e) {
e.printStackTrace();
}
}
private HttpURLConnection openConnection(String url, String method) throws IOException{
URL connectionURL = new URL(url);
HttpURLConnection connection = (HttpURLConnection)connectionURL.openConnection();
connection.setRequestMethod(method);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
return connection;
}
}
Finallty i see that the System.out.println("body data: " + buffer.toString()); is outputted two times
Well, i finally figured out what was going on...
i had a method
public synchronized boolean addValue(int id, int value){
Integer previous = values.put(id, value);
return previous.intValue() != value;
}
problem was that the first time, the put would return a NULL value and as soon as i took care of this method the error does not occur no more.

Java GetInputStream Method Not Returning Back

I have Java code that tests whether a proxy is of type SOCKS or HTTP, but I noticed that when it checks if it's SOCKS the code does not return after calling the method connection.getInputStream(). What is the cause of this problem and how can I solve it?
import java.io.*;
import java.net.*;
import java.util.*;
import org.apache.commons.codec.binary.Base64;
public class ProxyChecker {
private final int timeout = (10 * 1000);
public synchronized void check(String ip, int port, String username, String password) {
try {
InetSocketAddress proxyAddress = new InetSocketAddress(ip, port);
URL url = new URL("http://www.my-test-url-here.com/");
List<Proxy.Type> proxyTypes = Arrays.asList(Proxy.Type.SOCKS, Proxy.Type.HTTP);
for(Proxy.Type proxyType : proxyTypes) {
Proxy proxy = new Proxy(proxyType, proxyAddress);
try {
long time = System.currentTimeMillis();
URLConnection connection = url.openConnection(proxy);
connection.setReadTimeout(timeout);
connection.setConnectTimeout(timeout);
connection.setRequestProperty("User-Agent", "My User-Agent");
if(username != null && password != null) {
String encoded = new String(Base64.encodeBase64(new String(username + ":" + password).getBytes()));
connection.setRequestProperty("Proxy-Authorization", "Basic " + encoded);
}
String line = "";
// connection.getInputStream() not returning
System.out.println("Getting InputStream...");
InputStream in = connection.getInputStream();
System.out.println("Got InputStream.");
StringBuffer lineBuffer = new StringBuffer();
BufferedReader reader = new BufferedReader( new InputStreamReader( in ) );
while ((line = reader.readLine()) != null) {
lineBuffer.append(line);
}
String response = lineBuffer.toString();
System.out.println("Page: " + response);
reader.close();
in.close();
int elapse = (int)(System.currentTimeMillis() - time);
//If we get here we made a successful connection
if(proxyType == Proxy.Type.HTTP) {
System.out.println("Proxy is Type HTTP");
} else if(proxyType == Proxy.Type.SOCKS) {
System.out.println("Proxy is Type SOCKS");
}
} catch (SocketException se) {
se.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
ProxyChecker proxyChecker = new ProxyChecker();
//proxyChecker.check("127.0.0.1", 8080, "admin", "admin");
proxyChecker.check("127.0.0.1", 80, null, null);
}
}

Categories