Reputation: 13298
here's a minimal example of what I try to do :
public static String fetch () {
// get a connection to the website
HttpURLConnection connection = (HttpURLConnection)(new URL("http://example.com?param=ok").openConnection());
// configure the connection
connection.setRequestMethod("GET");
connection.setInstanceFollowRedirects(false);
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
// send the request
DataOutputStream ostream = new DataOutputStream(connection.getOutputStream());
ostream.flush();
ostream.close();
// receives the response
InputStream istream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(istream));
StringBuffer response = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
response.append('\r');
}
reader.close();
return response.toString();
}
To reach "http://example.com", the server sends a redirection first and HttpURLConnection automatically uses this redirection, then displays the response of this final dead-end page. I want to get the byte-code of this intermediary response. To do so, I tried to use the method setInstanceFollowRedirects and set to false (see the code). It seems to work since there is no output anymore but this is why I post here because there is no output anymore fuuuu
Does one have a fricking clue of why nothing is displayed when I try to output the return response.toString();
?
Upvotes: 0
Views: 69
Reputation: 13007
It is quite clear why you don't get a response string. You disabled to automatically follow redirects. So you will probably get a response which only consists of headers, no body. Your response string is collecting the bytes of the body and since there is no body in a response only saying "go to another location" your string is empty.
You should do connection.getResponseCode
and read the Location
header to know where to go next. Then you can create another request with this new location and you will get the "real" response.
I don't know what exactly you mean with "the byte code of intermediary response". I suppose you're interested in the header values. You can get all headers with connection.getHeaderFields()
. You iterate this map and collect all interesting header values for further processing.
Upvotes: 1