if (!request.query.equals("")) {
url += "?" + request.query;
}
HttpRequest target = new HttpRequest(requestPrefix + url);
// System.out.println("Fetching: " + requestPrefix + url);
if (proxyHost != null) {
target.setProxy(proxyHost, proxyPort);
}
target.setMethod(request.method);
HttpRequest.removePointToPointHeaders(request.headers, false);
request.headers.remove("if-modified-since"); // wrong spot XXX
request.headers.copyTo(target.requestHeaders);
/* XXX This doesn't belong here! - the proxy should do it */
target.requestHeaders.remove("host");
if (tokens != null) {
target.addHeaders(tokens, request.props);
}
target.requestHeaders.putIfNotPresent("Host",host);
boolean code=true;
try {
if (request.postData != null) {
OutputStream out = target.getOutputStream();
out.write(request.postData);
out.close();
}
// Connect to target and read the response headers
target.connect();
// System.out.println("Got headers: " + target.responseHeaders);
HttpRequest.removePointToPointHeaders(target.responseHeaders, true);
target.responseHeaders.copyTo(request.responseHeaders);
// Now filter the output, writing the header and content if true
request.log(Server.LOG_DIAGNOSTIC,
" Response headers: " + target.responseHeaders);
if (shouldFilter(request.responseHeaders)) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
target.getInputStream().copyTo(out);
request.log(Server.LOG_DIAGNOSTIC,
" parsing/modifying " + out.size() + " bytes");
byte[] content = modifyContent(request, out.toByteArray());
if (content == null) { // This is wrong!!
request.log(Server.LOG_DIAGNOSTIC,
" null content, returning false");
code=false;
} else {
request.sendResponse(content, null);
}
} else {
request.log(Server.LOG_DIAGNOSTIC, "Delivering normal content");
request.sendResponse(target.getInputStream(),
target.getContentLength(), null,
target.getResponseCode());
}
} catch (InterruptedIOException e) {
/*
* Read timeout while reading from the remote side. We use a
* read timeout in case the target never responds.
*/
request.sendError(408, "Timeout / No response");
} catch (UnknownHostException e) {
request.sendError(503, urlPrefix + " Not reachable");
} catch (ConnectException e) {
request.sendError(500, "Connection refused");
} catch (IOException e) {
request.sendError(500, "Error retrieving response: " + e);
e.printStackTrace();
} finally {
target.close();
// System.out.println("Finally (proxy): " + code);
}
return code;
}