Difference between Java Post Request and browser post request - java

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.

Related

how to send push notification to the android device using FCM by java server?

I have write this code for send notification using fcm by java server code. But it is throwing exception Server returned HTTP response code: 500 for URL: https://fcm.googleapis.com/fcm/send
public static void pushFCMNotification(String userDeviceIdKey) throws Exception{
String authKey = AUTH_KEY_FCM; // You FCM AUTH key
String FMCurl = API_URL_FCM;
URL url = new URL(FMCurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization","key="+authKey);
conn.setRequestProperty("Content-Type","application/json");
JSONObject json = new JSONObject();
json.put("to",userDeviceIdKey.trim());
JSONObject info = new JSONObject();
info.put("title", "Notificatoin Title"); // Notification title
info.put("body", "Hello Test notification"); // Notification body
json.put("notification", info);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(json.toString());
wr.flush();
wr.close();
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + json);
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();
/*OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(json.toString());
wr.flush();
conn.getInputStream();*/
}
According to the oficial documentation:
Errors in the 500-599 range (such as 500 or 503) indicate that there was an internal error in the FCM connection server while trying to process the request, or that the server is temporarily unavailable (for example, because of timeouts). Sender must retry later, honoring any Retry-After header included in the response. Application servers must implement exponential back-off.
source: https://firebase.google.com/docs/cloud-messaging/http-server-ref#interpret-downstream
However, make sure that the JSON request is properly formatted. Try to update your question with the json.toString() and check that your API key is still valid using the procedure described in: Checking the validity of a server key

OpenId Connect to Google gives me Http 400

Im trying to access to Google APIs using OAuth 2.0
but i always receive the http 400 when i try to get the token
I'm using Tomcat8 with Java SDK 8
And i don't know what is wrong.
private void sendPost(
final String code,
final String clientId,
final String clientSecret,
final String redirectUri,
final String grantType) throws Exception {
String url = "https://accounts.google.com/o/oauth2/token";
StringBuffer strb = new StringBuffer();
strb.append("code=" + code);
strb.append("&client_id=" + clientId);
strb.append("&client_secret=" + clientSecret);
strb.append("&redirect_uri=" + redirectUri);
strb.append("&grant_type=" + grantType);
String urlParameters = strb.toString();
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
con.setRequestProperty("Content-Length", String.valueOf(urlParameters.length()));
// 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());
}
My output is the following it seems that all parameters are ok.
Sending 'POST' request to URL : https://accounts.google.com/o/oauth2/token
Post parameters : code=<code>.InoAg9JcLi0boiIBeO6P2m94pmoskwI&client_id=<clientid>.apps.googleusercontent.com&client_secret=<secret>&redirect_uri=http://localhost:8080/Oauth/connect&grant_type=authorization_code
Response Code : 400
you'd want to url-encode the parameters
I don't think Google supports redirect_uri's pointing to "localhost" anymore so that would suggest that you got the "code" on a different redirect_uri than the one presented on the token endpoint request

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.

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