I have this piece of code:
String yourUrl = "https://api.discogs.com/oauth/request_token";
String currentSeconds = String.valueOf(System.currentTimeMillis() / 1000);
String urlString = yourUrl + "?oauth_consumer_key=BaeIqWMTmCxjeJjwmkJr&oauth_nonce=random_string_or_timestamp&oauth_timestamp="+ currentSeconds + "&oauth_callback=http://localhost:8080&oauth_signature=ZWglyBtJasnJBqVnzyduYJggCduKeYks;
System.out.println(urlString);
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("GET");
conn.setRequestProperty("User-Agent", "test");
int statusCode = conn.getResponseCode();
but I have this error:
Status Code: 401
Invalid signature. Expected signature base string: ZWglyBtJasnJBqVnzyduYJggCduKeYks&
According to the discogs oauth flow you shouldn't send params as request params, but rather should send it combined into Authorization header and do something like this:
String yourUrl = "https://api.discogs.com/oauth/request_token";
String currentSeconds = String.valueOf(System.currentTimeMillis() / 1000);
URL url = new URL(yourUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("User-Agent", "test");
conn.setRequestProperty("Authorization",
"OAuth oauth_consumer_key=\"BaeIqWMTmCxjeJjwmkJr\"," +
"oauth_nonce=\"" + System.currentTimeMillis() + "\"," +
"oauth_signature=\"ZWglyBtJasnJBqVnzyduYJggCduKeYks&\"," +
"oauth_signature_method=\"PLAINTEXT\"," +
"oauth_timestamp=\"" + currentSeconds + "\"," +
"oauth_callback=\"your_callback\""
);
int statusCode = conn.getResponseCode();
Related
I need to fetch the access token before making the actual call to the OAuth2-protected API.
As of now, I am doing it in the below fashion
String credential = clientId + ":" + clientSecret;
String encoding = Base64.getEncoder().encodeToString((credential).getBytes(‌"UTF‌​-8"​));
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Authorization", "Basic " + encoding);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty("Content-Length", Integer.toString(postDataLength));
Sonar says this is Non-Compliant RSPEC-2647, therefore I want to know what are the alternatives I can use, and how to fix this issue?
--EDIT
In the body, I was passing grant_type, username, and password.
I tried adding client_id and client_secret as well and it works.
Now I have one more question, is passing these credentials in the body more secure?
String body = "grant_type="+grantType+"&username="+username+"&password="+password+"&client_id="+clientId+"&client_secret="+clientSecret;
byte[] postData = body.getBytes(StandardCharsets.UTF_8);
int postDataLength = postData.length;
try(DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
wr.write(postData);
}
conn.connect();
I am trying a POST API, which works with cURL command or POSTMan. However, sending the same call through HttpURLConnection doesn't work.
Tried URL encoding the request params too. Still no luck. It's probably something wrong with the POST usage for HttpURLConnection.
String url = "CORRECT_URL";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
String urlParameters = "first_name=John&middle_name=Alfred&last_name=Smith&email=john.smith#gmail.com&phone=5555555555&zipcode=90401&dob=1970-01-22&ssn=543-43-4645&driver_license_number=F211165&driver_license_state=CA";
byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
int postDataLength = postData.length;
con.setRequestMethod("POST");
con.setRequestProperty("Authorization", "Basic AUTH_TOKEN=");
con.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty( "charset", "utf-8");
con.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
con.setUseCaches( false );
try {
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.write(postData);
wr.flush();
wr.close();
}
catch(Exception e) {
System.out.println("Server returned error!");
con.getResponseMessage();
}
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);
System.out.println("Response : " + con.getResponseMessage());
byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
...
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.write(postData);
is overkill.
PrintWriter out = new PrintWriter(
new OutputStreamWriter(con.getOutputStream(), "UTF-8")
);
out.print(urlParameters);
should do the job.
String httpsURL = "https://m.facebook.com/login/identify/?ctx=recover&c=https%3A%2F%2Fm.facebook.com%2Flogin%2F&lwv=100&_rdr";
String query = "email="+URLEncoder.encode("myemailaddress#gmail.com","UTF-8");
URL myurl = new URL(httpsURL);
HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-length", String.valueOf(query.length()));
con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0;Windows98;DigExt)");
con.setDoOutput(true);
con.setDoInput(true);
DataOutputStream output = new DataOutputStream(con.getOutputStream());
output.writeBytes(query);
output.close();
DataInputStream input = new DataInputStream( con.getInputStream() );
for( int c = input.read(); c != -1; c = input.read() )
System.out.print( (char)c );
input.close();
System.out.println("Resp Code:"+con .getResponseCode());
System.out.println("Resp Message:"+ con .getResponseMessage());
![enter image description here](https://i.stack.imgur.com/gVUc3.png)![enter image description here](https://i.stack.imgur.com/3RihL.png)
I made the below 2 changes to your code to make it work:
1) Removed the _rdr parameter from the end of the URL. Looks like when you add that, it always redirects you to the initial page. So:
String httpsURL = "https://m.facebook.com/login/identify/?ctx=recover&c=https%3A%2F%2Fm.facebook.com%2Flogin%2F&lwv=100";
2) When following redirects, HttpsURLConnection doesn't set cookies it got from the original response, unless you do this (More info):
CookieHandler.setDefault(new CookieManager());
Putting these two together, we have the final working code below. Here is a working demo. I added BufferedReader to read the response for slightly better looking console output, this is not necessary for it to work.
String httpsURL = "https://m.facebook.com/login/identify/?ctx=recover&c=https%3A%2F%2Fm.facebook.com%2Flogin%2F&lwv=100";
String query = "email=" + URLEncoder.encode("myemailaddress#gmail.com", "UTF-8");
CookieHandler.setDefault(new CookieManager());
URL myurl = new URL(httpsURL);
HttpsURLConnection con = (HttpsURLConnection) myurl.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-length", String.valueOf(query.length()));
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0;Windows98;DigExt)");
con.setDoOutput(true);
con.setDoInput(true);
DataOutputStream output = new DataOutputStream(con.getOutputStream());
output.writeBytes(query);
output.close();
BufferedReader input = new BufferedReader(new InputStreamReader(con.getInputStream()));
for (int c = input.read(); c != -1; c = input.read())
System.out.print((char) c);
input.close();
System.out.println("Resp Code:" + con.getResponseCode());
System.out.println("Resp Message:" + con.getResponseMessage());
Below is the Code Written by me.
But when i send the request i am getting Response Code 401 : Unathorized.
String url = "SAMPLE_URL";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
//con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
Add this code to your program after obj.openConnection();
String encoded = Base64.encode(username+":"+password);
con.setRequestProperty("Authorization", "Basic "+encoded);
Hi in my android project i m calling a webservice and sending get parameter through query string parameter , now problem is that if query string parameter value contains any white space then i am getting 505 error
URL url = new URL(urlstring.trim());
urlConnection = (HttpURLConnection) url.openConnection();
int response = urlConnection.getResponseCode();
I have one doubt if i use URLEncode(urlstring.trim(),"UTF-8")do i need to change my webservice code also ?
You should encode only the values of your params:
String urlString = "http://test.com?param1=" + URLEncoder.encode(value1, "UTF-8") + "¶m2=" + URLEncoder.encode(value2, "UTF-8") ;
URL url = new URL(urlstring.trim());
urlConnection = (HttpURLConnection) url.openConnection();
int response = urlConnection.getResponseCode();