URLConnection.setRequestProperty() not working? - java

I'm trying to integrate the Genius API into my Java program but I'm not entirely sure what I'm doing with making the actual HTTP request.
Here's the code I'm trying to use:
URLConnection connection = new URL("https://api.genius.com/search?q=juice").openConnection();
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Authorization", "Bearer TOKEN");
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
return content.toString();
(where TOKEN is my Genius auth token)
but I'm getting an IOException with a 403 forbidden message.
java.io.IOException: Server returned HTTP response code: 403 for URL: https://api.genius.com/search?q=juice
This same request worked when I tried with Hurl.it:
so I'm not exactly sure what's going on here. When I tried printing out the headers to see if they went through, I got this:
System.out.println("auth: " + connection.getHeaderField("Authorization"));
System.out.println("content: " + connection.getHeaderField("Content-Type"));
/** output */
auth: null
content: text/html; charset=UTF-8
I would appreciate any help here - thank you!!

Related

Java - doing post request to login page

Im trying to log in to https://flow.polar.com/login page using java. I did the post request with 'email' and 'password' value. I should be redirected to page to authorize geting data from the user, but insted im getting 200 response and im redirecting to main page (https://flow.polar.com). I was checking all the values in the browser request option,as I log in normally, but still got this bug.
My question is, is the anything im missing to log in, or is there a method to click sign in button?
I want to also add that when I provide wrong email or password im getting 400 response. So everything seems to work fine except im redirecting to wrong page :(
Here is my code:
URL obj = new URL(url);
HttpsURLConnection conn1 = (HttpsURLConnection) obj.openConnection();
// Acts like a browser
conn1.setUseCaches(false); // just going to main page instead of logging!!!
conn1.setRequestMethod("POST");
conn1.setRequestProperty("Host", "flow.polar.com");
conn1.setRequestProperty("User-Agent", USER_AGENT);
conn1.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn1.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
conn1.setRequestProperty("Accept-Language", "pl,en-US;q=0.7,en;q=0.3");
conn1.setRequestProperty("Connection", "keep-alive");
conn1.setRequestProperty("Referer", "https://flow.polar.com/login?n=D6FQQAAAAAAAAAAACXDM2CSAIAIABYDX3GB5XJTBP5IPEIESYYNNTUUOLAD6JXLR7H5G4EKE2WFJJ4MIOOLP54XGF6GJ4Q5T2G7HFWFJR7TUVNPDSEJLO6AKWH3WG3IIFTRKIJCZKVEAKMCJDSUPYZSUV2WYMDFU5CPBOIZJBGZGCAAAAA%3D%3D%3D%3D%3D%3D");
conn1.setDoOutput(true);
conn1.setDoInput(true);
// Send post request
DataOutputStream wr = new DataOutputStream(conn1.getOutputStream());
wr.writeBytes(postParams);
System.out.println(postParams);
wr.flush();
wr.close();
int responseCode = conn1.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + postParams);
System.out.println("Response Code : " + responseCode);
BufferedReader in =
new BufferedReader(new InputStreamReader(conn1.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
System.out.println("Response: ");
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
Okey. I got it working. The problem was that I didnt POST ALL input fileds. I forgot about hidden ones.
Here is working code:
Connection.Response response1 =
Jsoup.connect("https://flow.polar.com/login?n=XXX")
.userAgent(USER_AGENT)
.timeout(10 * 1000)
.method(Method.POST)
.data("email", "xxx#gmail.com")
.data("password", "passwd")
.data("returnUrl", "/?n=XXX")
.followRedirects(true)
.execute();

REST API Client response in java encoding trouble

I have a problem with an API call response in java.
See below the API response of my request, server replies with content that is unreadable as text:
Here is my code:
String urlt = "xxxxxx";
URL url = new URL(urlt);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.addRequestProperty("Accept-Encoding", "gzip");
conn.addRequestProperty("User-Agent", "okhttp/3.4.1");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
and an example of response headers:
With the following line, you tell the server that you are ready to accept a compressed response:
conn.addRequestProperty("Accept-Encoding", "gzip");
As shown in picture of response headers, the server obliges and gives you gzip-encoded (compressed) content.
But then you proceed to read the response, assuming it's just text... so yeah it prints as garbage in your console.
Either you remove that header above, or be ready to uncompress gzipped content.

Java POST Connection Timeout Using HttpsUrlConnection

I have a question about making a POST request with Java, and since this is my first attempt at something of this magnitude, please bear with me. I am working on a third party application in Java to connect to a website and make POST requests. Am I doing this correctly? Here is what I have so far:
Website Code:
(This is the code the website has for "bumping a trade" which simply sends 2 pieces of data to a php file. The URL is http://cdn.dota2lounge.com/script/trades.js)
function bumpTrade(trade, code) {
$.ajax({
type: "POST",
url: "ajax/bumpTrade.php",
data: "trade=" + trade + "&code=" + code
});
}
My Java Code:
private void sendPost() throws Exception {
//String url = "https://www.cdn.dota2lounge.com/script/ajax/bumpTrade.php";
String url = "https://www.cdn.dota2lounge.com/script/ajax/bumpTrade.php";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add request header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "trade=96510389&code=94cebd9";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
However I am receiving a connection timeout error when attempting to connect. I would be very grateful if someone could point me in the right direction!
The Java client code seems to be on the right track. But it looks like the URL in the code was the wrong URL.
Using the url "http://www.dota2lounge.com/ajax/bumpTrade.php" and HttpUrlConnection, I was able to get a 200 response (OK):
Sending 'POST' request to URL : http://www.dota2lounge.com/ajax/bumpTrade.php
Post parameters : trade=96510389&code=94cebd9
Response Code : 200
However nothing beyond that. Not sure of the API of the remote site but hopefully that's some help.

404 Error when sending HTTP request through java

I seem to be getting a 404 error when sending a http post to a sinatra server. I am trying to make the server page the text I send to it, here's my code I think it may be something wrong with my server but I'm not sure:
private void sendInfo() throws Exception {
//make the string and URL
String url = "http://localhost";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add request header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
//send post
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'post' request to url: " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response code: " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
and here is the sinatra server (ruby):
require 'sinatra'
get '/' do
'hello mate'
end
get '/boo' do
'trololo'
end
Could your problem be realated to trying to use a HTTPS (instead of HTTP) connections? I am looing at the use of HttpsURLConnection.
Since you're sending your HTTP request via POST, shouldn't your sinatra server routes bet post instead of get? Would explain why you're getting a 404. Something like this should sort it out:
require 'sinatra'
post '/' do
'hello mate'
end
post '/boo' do
'trololo'
end

Imgur API request using Java returns 400 status

I am trying to send a GET request to the Imgur API to upload an image.
When I use the following code I receive a 400 status response from the Imgur server - which, according to the Imgur error documentation, means I am missing or have incorrect parameters.
I know the parameters are correct as I have tested them directly in the browser URL (which successfully uploads an image) - so I must not be adding the parameters correctly within the code:
private void addImage(){
String data = URLEncoder.encode("image", "UTF-8") + "=" + URLEncoder.encode("http://www.lefthandedtoons.com/toons/justin_pooling.gif", "UTF-8");
data += "&" + URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode("myPublicConsumerKey", "UTF-8");
// Send data
java.net.URL url = new java.net.URL("http://api.imgur.com/2/upload.json");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
Logger.info( line );
}
wr.close();
rd.close();
}
This code is based on the API examples provided by Imgur.
Can anyone tell me what I am doing wrong and how I may resolve the problem?
Thanks.
In this sample, imgur service returns 400 Bad Request status response with a non-empty body because of incorrect API key. In case of non successful HTTP response you shold read the response body from an error input stream. For example:
// Get the response
InputStream is;
if (((HttpURLConnection) conn).getResponseCode() == 400)
is = ((HttpURLConnection) conn).getErrorStream();
else
is = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
And, by the way your example is POST, not GET, because you are sending the parameters in the request body instead of the URL.

Categories