Android HttpURLConnection: Handle HTTP redirects - java

I'm using HttpURLConnection to retrieve an URL just like that:
URL url = new URL(address);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setInstanceFollowRedirects(true);
// ...
I now want to find out if there was a redirect and if it was a permanent (301) or temporary (302) one in order to update the URL in the database in the first case but not in the second one.
Is this possible while still using the redirect handling of HttpURLConnection and if, how?

Simply call getUrl() on URLConnection instance after calling getInputStream():
URLConnection con = new URL(url).openConnection();
System.out.println("Orignal URL: " + con.getURL());
con.connect();
System.out.println("Connected URL: " + con.getURL());
InputStream is = con.getInputStream();
System.out.println("Redirected URL: " + con.getURL());
is.close();
If you need to know whether the redirection happened before actually getting it's contents, here is the sample code:
HttpURLConnection con = (HttpURLConnection) (new URL(url).openConnection());
con.setInstanceFollowRedirects(false);
con.connect();
int responseCode = con.getResponseCode();
System.out.println(responseCode);
String location = con.getHeaderField("Location");
System.out.println(location);

private HttpURLConnection openConnection(String url) throws IOException {
HttpURLConnection connection;
boolean redirected;
do {
connection = (HttpURLConnection) new URL(url).openConnection();
int code = connection.getResponseCode();
redirected = code == HTTP_MOVED_PERM || code == HTTP_MOVED_TEMP || code == HTTP_SEE_OTHER;
if (redirected) {
url = connection.getHeaderField("Location");
connection.disconnect();
}
} while (redirected);
return connection;
}

Related

java DataOutputStream POST without status code check doesn't post (POST not working) [duplicate]

I would like to open an URL and submit the following parameters to it, but it only seems to work if I add the BufferedReader to my code. Why is that?
Send.php is a script what will add an username with a time to my database.
This following code does not work (it does not submit any data to my database):
final String base = "http://awebsite.com//send.php?";
final String params = String.format("username=%s&time=%s", username, time);
final URL url = new URL(base + params);
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("User-Agent", "Agent");
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.connect();
But this code does work:
final String base = "http://awebsite.com//send.php?";
final String params = String.format("username=%s&time=%s", username, time);
final URL url = new URL(base + params);
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("User-Agent", "Agent");
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.connect();
final BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
connection.disconnect();
As far as I know. When you called the connect() function, it will only create the connection.
You need to at least call the getInputStream() or getResponseCode() for the connection to be committed so that the server that the url is pointing to able to process the request.

Any idea why this request works at curl and not in java?

I am trying to use the woocommerce APi with java,but it returns 403.When I try the same request by curl it works fine.
Already tried adding/removing request properties
Java class:
public static void main (String [] args){
String CONSUMER_KEY="consumer_key";
String CONSUMER_SECRET="consumer_secret";
String authString = CONSUMER_KEY + ":" + CONSUMER_SECRET;
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
HttpURLConnection conn;
try {
String url ="https://example.com/wp-json/wc/v3/products";
URL url1 = new URL(url);
conn = (HttpURLConnection) url1.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization","Basic "+authStringEnc);
conn.setRequestProperty("header","content-type:application/json");
conn.setRequestProperty("Accept", "*/*");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setInstanceFollowRedirects(false);
InputStream is = conn.getInputStream();
byte[] bytes = IOUtils.toByteArray(is);
String response= GzipUtil.unzip(bytes);
}
catch (Exception e){
}
}
Curl request:
curl https://example.com/wp-json/wc/v3/products \
-u {consumer_key}:{consumer_secret}
Any idea how to resolve this? Thank you
Some servers expect a User-Agent header to be present in the request to consider it as a valid request. So can you try to add that to your request?
conn.setRequestProperty("User-Agent", "My-User-Agent");

How to call subsequent request using j_security_check

How to call subsequent requests using j_security_check, I have followed below code but it's not working .
String url = "https://myhost/jsp/j_security_check?j_username=myuser&j_password=mypassword";
HttpURLConnection connection = (HttpURLConnection) new
URL(url).openConnection();
if (connection.getResponseCode() == 200) {
String cookie = connection.getHeaderField("Set-Cookie").split(";", 2)[0];
url = "https://myhost/getusers";
connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestProperty("Cookie", cookie);
connection.setRequestProperty("Cache-Control", "no-cache");
InputStream input = connection.getInputStream();
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String result = buffer.lines().collect(Collectors.joining("\n"));
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
Can anyone help me on it.

java how to send get request with header?

Hello guys I am trying to send get request in java with header. I am looking for a method like conn.addHeader("key","value); but I cannot find it. I tried "setRequestProperty" method but it doest not work..
public void sendGetRequest(String token) throws MalformedURLException, IOException {
// Make a URL to the web page
URL url = new URL("http://api.somewebsite.com/api/channels/playback/HLS");
// Get the input stream through URL Connection
URLConnection con = url.openConnection();
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Cache-Control", "no-cache");
con.setRequestProperty("Authorization", "bearer " + token);
InputStream is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
// read each line and write to System.out
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
It returns Httpresponse 401 error.
My office mate use unity c# to send get request header his codes looks like the fallowing.
JsonData jsonvale = JsonMapper.ToObject(reqDataGet);
// Debug.Log(jsonvale["access_token"].ToString());
// /*
string url = "http://api.somewebsite.com/api/channels/playback/HLS";
var request = new HTTPRequest(new Uri(url), HTTPMethods.Get, (req, resp) =>
{
switch (req.State)
{
case HTTPRequestStates.Finished:
if (resp.IsSuccess)
{
}
break;
}
});
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("Authorization", "bearer " + jsonvale["access_token"].ToString());
request.Send();
Any help?
In Java I think you want something like this.
String url = "http://www.google.com/search?q=stackoverflow";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", "My Example" );
int responseCode = con.getResponseCode();

Malformed request exception when trying to send GET request

I'm trying to connect to GDAX using their REST API.
I first want to do something very simple, i.e. getting historic rates.
I tried this:
private static final String GDAX_URL = "https://api.gdax.com";
public String getCandles(final String productId, final int granularity) {
HttpsURLConnection connection = null;
String path = "/products/" + productId + "/candles";
try {
//Create connection
URL url = new URL(GDAX_URL);
connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("granularity", String.valueOf(granularity));
connection.setUseCaches(false);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(path);
wr.close();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
StringBuffer response = new StringBuffer();
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
System.out.println(response.toString());
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
return null;
}
But I get a 400 code in return "Bad Request – Invalid request format".
My problem is with the passing of the path "/products//candles" and the parameters (e.g. granularity).
I don't understand what should go in the request properties and in the message itself, and in what form.
I managed to make it work like this:
URL url = new URL(GDAX_URL + path + "?granularity="+granularity);
connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json");
Not sure how to use the DataOutputStream, so I just removed it. At least it works.

Categories