401 Encountered when generating token with client_credentials Java 6 EE - java

I tried to use the following method which is used in other areas of the app but I still get 401:
The original question is posted here: Java 6 EE Client Credentials Bearer
String urlParameters = "client_id=CLIENT_ID&client_secret=CLIENT_SECRET&grant_type=client_credentials";
byte[] postData = urlParameters.getBytes("UTF-8");
int postDataLength = postData.length;
String TokenURL = "URL for getting the token here";
URL url = new URL(TokenURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty("Content-Length", Integer.toString(postDataLength));
conn.setUseCaches(false);
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.write(postData);
wr.flush();
System.out.println("->->-> We will send: " + urlParameters);
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED && conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
System.out.println("->->-> Returned Http Code: " + conn.getResponseCode());
throw new RuntimeException("Failed : HTTP error code for Getting Token XFORMURLENCODED : " +
conn.getResponseCode());
}

Related

set the (OAuth token) Authorization Header on SpringBoot

I have to send a Get Request to Request the Token URL with these Headers:
Content-Type: application/x-www-form-urlencoded
Authorization:
OAuth oauth_consumer_key="your_consumer_key",
oauth_nonce="random_string_or_timestamp",
oauth_signature="your_consumer_secret&",
oauth_signature_method="PLAINTEXT",
oauth_timestamp="current_timestamp",
oauth_callback="your_callback"
User-Agent: some_user_agent
I've tried with this piece of code:
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization: OAuth oauth_consumer_key", "BaeUqWMTmCxjeJj9mkJr");
conn.setRequestProperty("Authorization: oauth_nonce", "random_string_or_timestamp");
conn.setRequestProperty("Authorization: oauth_signature", "ZWglyBtJasnJBqVndzyduYJggCduKeYks&");
conn.setRequestProperty("Authorization: oauth_timestamp", String.valueOf(new Date()));
conn.setRequestProperty("Authorization: oauth_callback", "http://localhost:8080");
conn.setRequestProperty("User-Agent", "test");
int statusCode = conn.getResponseCode();
System.out.println("Response from WA Gateway: \n");
System.out.println("Status Code: " + statusCode);
BufferedReader br = new BufferedReader(new InputStreamReader(
(statusCode == 200) ? conn.getInputStream() : conn.getErrorStream()
));
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
But I get this error:
Illegal character(s) in message header field: Authorization: OAuth oauth_consumer_key
The problem is that you're not forming your request correctly. Since it's a GET version of OAuth request, here's an example from RFC5849 on how to do this
GET /example/path?oauth_consumer_key=0685bd9184jfhq22&
oauth_token=ad180jjd733klru7&oauth_signature_method=HM
AC-SHA1&oauth_signature=wOJIO9A2W5mFwDgiDvZbTSMK%2FPY%
3D&oauth_timestamp=137131200&oauth_nonce=4572616e48616
d6d65724c61686176&oauth_version=1.0 HTTP/1.1
Sp, set an Authorization header in the setRequestProperty following the format above:
...
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
String yourUrl = "http://yourwebsite.com";
String currentSeconds = 1618496867; // current seconds
String authorizationValue = "OAuth oauth_consumer_key=\"BaeUqWMTmCxjeJj9mkJr\",
oauth_nonce=\"1618496867\",
oauth_signature=\"ZWglyBtJasnJBqVndzyduYJggCduKeYks&\",
oauth_signature_method=\"PLAINTEXT\",
oauth_timestamp=\"1618496867\",
oauth_callback=\"http://localhost:8080\""
conn.setRequestProperty("Authorization", authorizationValue);
conn.setDoOutput(true);
conn.setRequestMethod("GET");
...
I tested a similar request using a Postman client for my OAuth authentication server and it worked perfectly.
These are not headers, you have to compute it.. Like this
https://twittercommunity.com/t/solved-java-oauth-request-token-flow-example-without-libraries/1440

Send JSON data through POST in Java

I have this code to send JSON data (passed as a string) to the server (This code works when English characters are to be sent as values in dataJSON as far as I tested):
private static String sendPost(String url, String dataJSON) throws Exception {
System.out.println("Data to send: " + dataJSON);
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
String type = "application/json;charset=utf-8";
// add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Content-Length", String.valueOf(dataJSON.getBytes("UTF-8").length));
con.setRequestProperty("Content-Type", type);
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeUTF(dataJSON);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
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();
System.out.print("Response string from POST: " + response.toString() + "\n");
return response.toString();
}
Problem is I don't get correct response, which I get for example using DHC Restlet Client.
The problem is I think the dataJSON must be encoded in UTF8. That's how the server expects it most likely.
But it seems I have some problem in code the way I try to convert it and send it.
Can someone help me send data in body as UTF8 string in above example?
I think I solved with this approach:
private static String sendPost2(String urlStr, String dataJSON) throws Exception {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
OutputStream os = conn.getOutputStream();
os.write(dataJSON.getBytes("UTF-8"));
os.close();
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
String result = new BufferedReader(new InputStreamReader(in)) .lines().collect(Collectors.joining("\n"));
in.close();
conn.disconnect();
return result;
}
Please suggest alternative if you see problem with it.

How to Send API header request through Selenium and get response back

I have to automate API through selenium+TestNG (Java). I know its not a good habit to automate APIs using selenium code but still I have got this to do.
Scenario - there is a login API and have to send the email and password and get response back (response code 200). Also can we print the response information also?
If you are working on java you can use JAVA socket libraries for the same:
Here are the sample code for POST API:
URL obj = new URL(url);
con = (HttpsURLConnection) obj.openConnection();
// add request header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
String urlParameters = "j_username=" + user + "&j_password=" + pass
+ "";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
For GET API:
obj = new URL(url);
obj.openConnection();
con = (HttpsURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
CookieHandler.setDefault(new CookieManager());
// add request header
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.8l");
con.setRequestProperty("Accept", "*/*");
con.setRequestProperty(
"Cookie",
"BIGipServerPRODCAN-Default=423078080.2087.0000; __utma=44365112.1659763098.1418886605.1427784911.1441869730.4; __utmc=44365112; __utmz=44365112.1427784911.3.2.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided); JSESSIONID="
+ cookieValue);
responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
File file = new File(prop.getFilePath() + "//XMLs//" + fileName
+ ".xml");
file.delete();
FileWriter fstream = new FileWriter(prop.getFilePath() + "//XMLs//"
+ fileName + ".xml", true);
BufferedWriter out = new BufferedWriter(fstream);
while ((inputLine = in.readLine()) != null) {
out.write(inputLine.toString());
out.newLine();
response.append(inputLine);
}
in.close();
out.close();`

Implementing Sign in with Twitter

I am trying to implement Twitter sign in in my java web application.
I am following this manual.
I registered my application at here.
But when i am trying to get request_token i am getting Response Code : 401.
I am using following code to get request_token.
String userUrl = "https://api.twitter.com/oauth/request_token";
String urlParam = oauth_callback + "&" + oauth_consumer_key + "&" + oauth_nonce + "&"+ oauth_signature + "&" + oauth_signature_method+"&"+oauth_timestamp+"&"+oauth_version;
URL url = new URL(userUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = urlParam;
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
As the doc suggests, you have to put these "urlparams" in the headers, not in the URL parameters :
https://dev.twitter.com/oauth/reference/post/oauth/request_token
You might also find this useful: Implement OAuth in Java

How to set Content Length REST Request - for Android

I'm trying to connect to a webservice using Java and REST. This is what I've tried, and I get a 411 error.
public static String getSiteToken(String host,String token) throws IOException, JSONException
{
host = host.replace("https://", "http://");
URL url = new URL(host + "/tokens");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", token);
conn.setRequestProperty("Content-Length", "57");
//conn.setFixedLengthStreamingMode(57);
conn.setRequestProperty("Connection","keep-alive");
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader rd = new BufferedReader(isr);
JSONObject json = new JSONObject(rd.readLine());
rd.close();
conn.disconnect();
return json.getString("token");
}
I also tried " setFixedLengthStreamingMode " method, but the application wasn't responding after that line of code. Everything works fine when connecting with REST Client for firefox. I can't figure it out. Thanks!
You aren't writing anything to the body of the request. In that case the content length should be 0 and not 57

Categories