Setting custom header using HttpURLConnection - java

I am simply making a GET request to a Rest API using HttpURLConnection.
I need to add some custom headers but I am getting null while trying to retrieve their values.
Code:
URL url;
try {
url = new URL("http://www.example.com/rest/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// Set Headers
conn.setRequestProperty("CustomHeader", "someValue");
conn.setRequestProperty("accept", "application/json");
// Output is null here <--------
System.out.println(conn.getHeaderField("CustomHeader"));
// Request not successful
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new RuntimeException("Request Failed. HTTP Error Code: " + conn.getResponseCode());
}
// Read response
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer jsonString = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
br.close();
conn.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
What am I missing?

It is a good idea to send
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("CustomHeader", token);
instead of
// Set Headers
conn.setRequestProperty("CustomHeader", "someValue");
conn.setRequestProperty("accept", "application/json");
Both the type value and header should be changed.
it works in my case.

The conn.getHeaderField("CustomHeader") returns the response header not the request one.
To return the request header use: conn.getRequestProperty("CustomHeader")

Related

How to follow redirect other link with server's post in spring

I'm connecting with two local servers post parameters for redirect link. But not change url and web view after posting the parameters. I get only response.toString() (html string like ...."). How I change redirect link and view.
I found other questions and answers that are not easy to understand.
try {
HttpURLConnection connection = null;
URL url = new URL("http://localhost:9090/myproject/payreq");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", ""
+ Integer.toString(postParams.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(connection
.getOutputStream());
wr.writeBytes(postParams);
wr.flush();
wr.close();
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
I expect change my project link's 8080 from redirect follow other sites.
If you want to redirect to a different server, completetely on the server side, without the user noticing a change in the browser URL, use forward: redirection:
#Controller
public class MyController {
#RequestMapping("/myurl")
public String redirectWithUsingForwardPrefix(ModelMap model) {
model.addAttribute("attribute", "forwardWithForwardPrefix");
return "forward:/http://localhost:9090/myproject/payreq";
}
}

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.

POST to Google Cloud Messaging with Retrofit

I am using HttpURLConnection for POST message to GCM like:
try {
URL url = new URL(GCM_SERVER_URL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "key=" + apiKey);
conn.setDoOutput(true);
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
DataOutputStream dataOutputStream = new DataOutputStream(conn.getOutputStream());
mapper.writeValue(dataOutputStream, content);
dataOutputStream.flush();
dataOutputStream.close();
// Get the response
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
And now i want to use Retrofit for POST message to GCM
I tried:
#Headers("Content-Type: application/json")
#FormUrlEncoded
#POST("/")
public GCMObject GCMAuthorization(#Header("Authorization") String apiKey,
#Body String data
);
I sent json string in data, But it always failed with this error:
#Body parameters cannot be used with form or multi-part encoding.
I did't found any solution, how can i fix it?
#FormUrlEncoded is used when you want to send form parameters. These parameters are encoded as the body, you can have your own. It does not look like you are using and form parameters, so remove #FormUrlEncoded. Also, I recommend using GSON to convert your POJO to JSON for the #Body. It looks like you are using retrofit 1 and trying to send a raw String. Retrofit will try to JSON encode that for you, which means you'll end up with the object you send wrapped in "...". If you want to send a raw string, take a look at this answer for your options in retrofit 1.

Flask not receiving POST from Android

I used to use DefaultHttpClient for my networking code, but decided to change to HttpURLConnection.
I have searched for other questions on how to send POST messages (eg How to add parameters to HttpURLConnection using POST), but for some reason my Flask app always gives me error 400.
When I use logcat, it indeed displays that my POST message is "username=asdf&password=asdf". I include the code below. Also, if I initialized the cookieManager in the method that called this method (makeServiceCall), will returning cookieManager keep my session for subsequent calls to makeServiceCall?
public CookieManager makeServiceCall(CookieManager cookieManager, String urlString, int method, List<NameValuePair> db) {
String charset = "UTF-8";
try {
URL url = new URL(urlString);
if (method == POST) {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
if (db != null) {
try {
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Accept-Charset", charset);
urlConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(out, charset));
Log.d("log", "> " + getQuery(db));
writer.write(getQuery(db));
writer.flush();
writer.close();
out.close();
//Get Response
InputStream in = urlConnection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(in));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
Log.d("Read attempt: ", "> " + response.toString());
}
finally {
urlConnection.disconnect();
}
}
}
etc.
Flask code:
def login():
error = None
if request.method == 'POST':
if request.form['username'] != app.config['USERNAME']:
error = 'Invalid username'
elif request.form['password'] != app.config['PASSWORD']:
error = 'Invalid password'
else:
session['logged_in'] = True
flash('You were logged in')
return redirect(url_for('show_entries'))
return render_template('login.html', error=error)

Categories