Java POST Connection Timeout Using HttpsUrlConnection - java

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.

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();

How to wait for Expect 100-continue response in Java using HttpURLConnection

I am stuck using HttpURLConnection to make a PUT http request to a web-server. I have some code that will make a PUT request just fine, and I can trivially include the 'Expect 100-continue Request Property' in the headers however try as I might I can't seem to make the function wait for the '100 Continue' response from the server before sending the actual http payload.
I get the following (from Wireshark)
PUT /post/ HTTP/1.1
User-Agent: curl/7.35.0
Accept: */*
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue
Host: somerandomdomain.info
Connection: keep-alive
Content-Length: 17
Some data for you
HTTP/1.1 100 Continue
...rest of web-server response...
I'm sure I am missing something obvious however after googling I have drawn a blank - can anyone help?
Many thanks if so :)
Http PUT code snippet below:
String url = "http://somerandomdomain.info";
String postJsonData = "Some data for you\n";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// Setting basic post request
con.setRequestMethod("PUT");
con.setRequestProperty("User-Agent", "jcurl/7.35.0");
con.setRequestProperty("Accept", "*/*");
con.setRequestProperty("Content-Length", postData.length() + "");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Expect", "100-continue");
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(postData);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post Data : " + postData);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String output;
StringBuffer response = new StringBuffer();
while ((output = in.readLine()) != null) {
response.append(output);
}
in.close();
//printing result from response
System.out.println(response.toString());
It's not obvious to me why they designed it this way, but the code that implements the Expect:100 logic is only used if you have called one of setFixedLengthStreamingMode(int contentlen) or the overload for long or setChunkedStreamingMode(int chunklen) before doing getOutputStream. In this case I recommend the first as simplest.

Difference between Java Post Request and browser post request

I am trying to use api of one popular russian social networks. I am using OAuth via Java HttpUrlConnection. The problem is, when I send post data via Java, I get 401 response code. When I copy request and paste it browser, I get redirect to URL containing access token I need. That means that my post request is correct, but why when I send it with Java I get 401 error? When I send request with incorrect password, I get 200. It means that request is correct too.
private void getHomeAuth() throws Exception {
String url = "https://oauth.vk.com/authorize?client_id=APP_ID&scope=friends&redirect_uri=https://oauth.vk.com/blank.html&display=page&v=5.34&response_type=token";
URL oauth = new URL(url);
HttpURLConnection connection = (HttpURLConnection) oauth.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = connection.getResponseCode();
System.out.println("Response code: " + responseCode);
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while((inputLine = reader.readLine()) != null)
response.append(inputLine + "\n");
reader.close();
PrintWriter writer = new PrintWriter("auth.html");
writer.print(response);
writer.close();
parse();
cookies = connection.getHeaderField("Set-Cookie");
referer = connection.getURL().toString();
}
private void postAuth() throws Exception {
email = URLEncoder.encode("example#gmail.com", "UTF-8");
password = "password";
_origin = URLEncoder.encode(_origin, "UTF-8");
String url = "https://login.vk.com/?act=login&soft=1";
URL post = new URL(url);
String urlParameters = "ip_h=" + ip_h + "&_origin=" + _origin + "&to=" + to + "&expire=" + expire + "&email=" + email + "&pass=" + password;
HttpsURLConnection con = (HttpsURLConnection) post.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Cookie", cookies);
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("Sent post. Response code: " + responseCode + "\nRequest: " + post.toString() + urlParameters + "\nRequestMethod: " + con.getRequestMethod());
}
I also tryied to send this request via addon in browser, and the result was correct. I obtained access token from redirect link.
Maybe the problem is that something inside request is incorrect. I have tried to monitor requests from java app, but I failed.
My experience with this kind of problem is that the http request that first authenticates the user also puts cookies (scope varies from case to case) into the response and subsequent http requests are expected to contain those cookies. Look very closely at the complete returned response headers to see what cookies might have been returned.

post requests to google fusion tables

I've been trying to insert new rows in my google fusion table, but in response I obtain a 401 error; also any other post request doesn't work.
I've already put the oauth access token, and also the api key, here is the code:
private void sendPost() throws Exception {
String url = "https://www.googleapis.com/fusiontables/v1/query?sql= **here I put my query** ?key="+ "**here I put my api key**";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add request header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Chrome/11.0.660.0");
con.addRequestProperty("client_id", "**here I put my client_ID**");
con.addRequestProperty("client_secret", "**here I put my client_secret**");
con.setRequestProperty("Authorization","Oauth " + "**here I put my access token**");
con.setRequestProperty("Content-Type", "application/json");
String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
// 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(newInputStreamReader(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());
}
}
Can you tell me if the code is wrong and in which point?
Thank you in advance.
Two separate requests are required:
a first POST request, to get the OAuth token. The body containing client_id, client_secret, redirect_uri, grant_type and the authorization_code.
a second POST request with body being the SQL command. In this case, INSERT INTO TableID (field1, field2, ...) VALUES (value1, value2, ...). This request needs the Authentication header token.

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

Categories