I have been trying hard to figure this out by creating a ServerSocket, Listening for incoming cient response and using clientwriter/printwriter to write to the output stream of the client but the browser does not show the response(headers and body)... here is a snippet in my code
byte[] buffer = new byte[buffer_size];
BufferedInputStream clientIstream = new BufferedInputStream(client.getInputStream());
BufferedWriter clientWriter = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
clientIstream.read(buffer);
String clientRequest = new String(buffer);
Log.d(TAG, "request: "+clientRequest);
String host = getHostFromRequest(clientRequest);
Log.d(TAG, "the host is "+host);
String hostSite=host.split(":")[0];
//internet = new Socket(host, port);
URL url=new URL("http://"+hostSite);
//URL url2=new URL()
connection=(HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode=connection.getResponseCode();
String responseMessage=connection.getResponseMessage();
Log.d(TAG, "code: "+responseCode+" response: "+responseMessage);
// Send response status line to the client
clientWriter.write("HTTP/1.1 " + responseCode + " " + responseMessage + "\r\n");
clientWriter.flush();
// Forward response headers to the client
for (String header : connection.getHeaderFields().keySet()) {
if (header != null) {
for (String value : connection.getHeaderFields().get(header)) {
clientWriter.write(header + ": " + value + "\r\n");
Log.d(TAG, "headers++ "+header+":"+value);
}
}
}
clientWriter.write("\r\n");
clientWriter.flush();
// Forward the response body to the client
InputStream inputStream = connection.getInputStream();
OutputStream outputStream = client.getOutputStream();
byte[] myBuffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(myBuffer)) != -1) {
// Check if the client is still connected
if (client.isConnected()) {
outputStream.write(myBuffer, 0, bytesRead);
} else {
// If the client is no longer connected, break out of the loop
break;
}
}
outputStream.flush();
Browser displays nothing but rather says (url) did not send back a valid response