I am having trouble getting a 401 unauthorized response from the server,I am doing a "GET" call from a ruby on rails api the oauth token is in the header like this.
urlConnection = (HttpURLConnection) url.openConnection();
OAuth = "bearer " + Base64.encodeToString(userpass.getBytes(), Base64.NO_WRAP);
Log.e("auth", oAuth_token);
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("Authorization", OAuth);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.connect();
Userpass is the actual token.
This works in postman as well as on iOS but android is getting a 401
The Bearer Token Usage specification (RFC 6750) is a bit confusing. You don't have to base64-encode the access token before use. To be concrete, your code should be simply like this:
OAuth = "Bearer " + userpass;
See this discussion where the questioner confessed he had had the same confusion as yours.
Related
I want to post the request in same formate.
POST /mga/sps/oauth/oauth20/token HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded
Authorization: Basic aaabbbCCCdddeeefffGGG
client_id=xxx&client_secret=yyy&grant_type=authorization_code
&code=3v6MJzt9vKtRkxpTFnkJG3IyspWC2k
&redirect_uri=xyz%2Ffolder
I have Implemented but getting bad request and unable to print the post content what I am sending I also want to get the json response after sending this request.
String urlParameters = "grant_type=authorization_code"+"&redirect_uri="+session.getAttribute("redirect_uri")+"&code_verifier="+session.getAttribute("codeVerifier")+"&code="+session.getAttribute("code")+"&state="+session.getAttribute("state");
byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
int postDataLength = postData.length;
URL url = new URL( "https://example/oauth20/token" );
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.setRequestProperty("Host","example.com");
conn.setRequestProperty("Authorization","clientID=xyz");
conn.setUseCaches(false);
DataOutputStream wr = new
DataOutputStream(conn.getOutputStream());
wr.write(postData);
System.out.println(conn.getResponseCode());
System.out.println(conn.getResponseMessage());
conn.disconnect();
You have multiple options.
You can start with Java HTTP Client - Refer
The HTTP Client was added in Java 11. It can be used to request HTTP
resources over the network. It supports HTTP/1.1 and HTTP/2, both
synchronous and asynchronous programming models, handles request and
response bodies as reactive-streams, and follows the familiar builder
pattern.
Apache HttpClient - Refer
RestTemplate - Refer
JAX-RS Client - Example
Spring 5 WebClient - Example
OkHttpClient - Example
Comparison
I'm having a hard time using the Java HttpURLConnection. Ive tried using HttpClient but that also failed.
All I want to do is this:
curl -H "Authorization: Bearer 1111111111" https://company.aha.io/api/v1/features/APP-1
1111111111 is the API key.
This is my code so far.
URL url = new URL("https://company.aha.io/api/v1/features/APP-1");
connection = (HttpsURLConnection) url.openConnection();
//add request header for authentication
connection.setRequestProperty("Authorization", "Bearer " + token);
connection.connect();
System.out.println(connection.getResponseCode());
I keep getting a 404 code.
Thank you for the help.
I am trying to create an Asset on Azure Media Services using REST API from Android. I am following this documentation and this is my code to connect with AMS endpoint from Android,
urlConnection = (HttpURLConnection) this._url.openConnection();
urlConnection.setRequestProperty("Content-Type", String.valueOf("application/json"));
urlConnection.setRequestProperty("DataServiceVersion", String.valueOf("1.0;NetFx"));
urlConnection.setRequestProperty("MaxDataServiceVersion", String.valueOf("3.0;NetFx"));
urlConnection.setRequestProperty("Accept", String.valueOf("application/json"));
urlConnection.setRequestProperty("Accept-Charset", String.valueOf("UTF-8"));
urlConnection.setRequestProperty("Authorization", String.format(Locale.ENGLISH, "Bearer %s", _token));
urlConnection.setRequestProperty("x-ms-version", String.valueOf(2.11));
urlConnection.setRequestProperty("x-ms-client-request-id", UUID.randomUUID().toString());
urlConnection.setRequestProperty("Host", this._host);
urlConnection.setRequestProperty("Content-Length", String.valueOf(this._postData.length));
urlConnection.setRequestProperty("Expect", String.valueOf("100-continue"));
urlConnection.setConnectTimeout(CONNECTION_TIME_OUT);
urlConnection.setReadTimeout(CONNECTION_READ_TIME_OUT);
urlConnection.setInstanceFollowRedirects(true);
urlConnection.setRequestMethod("POST");
urlConnection.setUseCaches(false);
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
OutputStream wr= urlConnection.getOutputStream();
wr.write(_postData);
wr.flush();
wr.close();
And my _postData variable is byte array which I am converting from json,
_fileName = _fileName.replace(" ", "-");
JSONObject jo = new JSONObject();
jo.put("Name", _fileName+".mp4");
jo.put("Options", String.valueOf(0));
this._postData = jo.toString().getBytes("UTF-8");
I have tried using Google Chrome's REST api client extension to check the post request and It works fine. I got the response I was expecting from chrome's REST api client extension but using Android, I am not getting the same response. I am getting this response from this code which is the step I have already performed before running this code. I have used both endpoints https://media.windows.net/ and https://wamsbayclus001rest-hs.cloudapp.net/ but it is not working from Android. I believe that Android is changing Headers or something is wrong with headers that AMS not parsing properly. Can anyone guide me how to achieve this using Android HttpUrlConnection?
Thanks.
I fixed it by changing OutputStream to DataOutputStream
DataOutputStream wrr = new DataOutputStream(urlConnection.getOutputStream());
wrr.write(this._postData);
wrr.flush();
wrr.close();
and changed my json array to string,
String s = "{\"Name\":\"" + _fileName + ".mp4\", \"Options\":\"0\"}";
and it worked fine.
I am creating a django rest api, and I'm trying to send JSON data via PUT request from an Android device, using HttpUrlConnection.
URL url = new URL(myurl);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("PUT");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setRequestProperty("Accept", "application/json");
Log.v("Apiput", MainActivity.cookieManager.getCookieStore().getCookies().get(0).toString());
conn.connect();
if(conn.getResponseCode() != 200) {
return "" + conn.getResponseCode();
}
OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream());
osw.write(put);
osw.flush();
osw.close();`
I know I have to send a csrf token, but I think that I'm sending it already.
By examining the META in my request I can see the csrf token both in headers and cookies:
'HTTP_COOKIE': 'csrftoken=3jLNzfLIu1P5dBH4WWwggHMH7oDQC7Rx;'
And in my android device i have a CookieManager that says that the csrf cookie has the same value.
V/Apiputīš csrftoken=3jLNzfLIu1P5dBH4WWwggHMH7oDQC7Rx
I am getting a 403 (Forbidden) Http error besides the user is authenticated (I can make GET Requests)
[26/Sep/2015 00:16:04]"PUT /api/works/34/ HTTP/1.1" 403 58
With curl I am able to send the request without any problem, with the same user credentials.
I wonder if anyone can tell me what am I doing wrong.
Thanks.
You don't have to set the cookie if you're doing a JSON call to Django REST framework.
It would definitively help if you can provide the permissions associated to the view.
Can someone please explain how exactly the user credentials are passed to the server in the below code...
URL urlObj = new URL("https://javaguy.com");
HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection(); conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "text/xml");
String userPassword = username + ":" + password;
byte[] authEncBytes = Base64.encodeBase64(userPassword.getBytes());
String authStringEnc = new String(authEncBytes);
conn.setRequestProperty("Authorization", "Basic " + authStringEnc);
Is it part of the HTTP header? Just curious.
Thanks in advance.
You've answered your own question, but yes. The "Authorization" is part of the header.
You can read more about basic authentication on the wikipedia.
Then the javadoc isn't super clear, but the setRequestProperty should add the new property to the request header.
As a side note, I would urge you to consider using a library like HttpClient if you're planning on doing any http requests in a production system. Working directly with URL and URLConnection directly can be tricky. HttpClient isn't super easy to work with either, but it is easier then URL/URLConnection.
There are two HttpClient libraries, make sure you're working with version 4 (which is the latest version at the time of this post) and not version 3.