cz.msebera.android.httpclient.client.HttpResponseException: Unauthorized - java

Hello I'm trying to build a Clima app and I'm Using OpenWeatherMap Api
to retrieve weather data from the internet.
When I try the app on a physical device, I got this message error:
cz.msebera.android.httpclient.client.HttpResponseException: Unauthorized
I tried to generate a new API key but the same problem.
// TODO: Add letsDoSomeNetworking(RequestParams params) here:
protected void letsDoSomeNetworking(RequestParams params) {
AsyncHttpClient client = new AsyncHttpClient();
client.get(WEATHER_URL, params, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode ,Header[] header , JSONObject response){
Log.d("Clima", "onSuccess: " + response.toString());
}
public void onFailure (int statusCode , Header[] headers , Throwable e , JSONObject response){
Log.d("Clima", "Onfailure: " + statusCode);
Log.d("Clima", "fail: " + e.toString());
Toast.makeText(WeatherController.this, "requestFialed " , Toast.LENGTH_SHORT).show();
}
});
}

i think it s highly like you didn't change this variable
final String APP_ID = "e****************************a"; on the weathercontroller.java
you're supposed to write yout own app_id , you can your own key by signing up at
http://api.openweathermap.org/ , you will get the app_id on your email and the key will be activated within 1hour or 2 . best of luck buddy!

Related

Request body is null in Android Networking

I am trying to send some data using Android Networking library but the request body is null. Tried sending the data using Postman directly and it worked fine but when I use the code below it returns a 400 bad request error.
AndroidNetworking.post(API.BASE_URL + "savefile/postlog")
.addHeaders("Authorization", "Bearer " + token)
.addHeaders("Accept", "multipart/form-data")
.setContentType("multipart/form-data")
.addBodyParameter(logAPIData)
.setTag("Logs").setOkHttpClient(API.getUnsafeOkHttpClient())
.setPriority(Priority.HIGH)
.build().getAsOkHttpResponse(new OkHttpResponseListener() {
#Override
public void onResponse(Response response) {
if (!response.isSuccessful()) {
sendToSQLite();
}
requireActivity().onBackPressed();
}
#Override
public void onError(ANError anError) {
Log.d(TAG, "Error: " + anError.getLocalizedMessage());
}
});
}

How to call List Item in SharePoint Using REST API in Android?

I'm want to consume share point rest API service to call from Android previously i use to call share point web service through the graph API but while generating token from graph API its not support in below URL, does any one have any solution about this problem.
https://mysharepoint.sharepoint.com/sites/MySite/_api/web/lists/getbytitle('Announcements')/Items
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, MSGRAPH_URL,
parameters,new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
/* Successfully called graph, process data and send to UI */
Log.d(TAG, "Response: " + response.toString());
updateGraphUI(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error: " + error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "Bearer " + authResult.getAccessToken());
return headers;
}
};
Log.d(TAG, "Adding HTTP GET to Queue, Request: " + request.toString());
request.setRetryPolicy(new DefaultRetryPolicy(
3000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(request);
I already tried with MSAL library but its does not work with this token.
Update: i used to call graph api for janrating token but i got 401 error with this above mention URL.
You are calling a SharePoint API, so you will need a SharePoint token instead of a Graph token. These are two separate APIs with different authentications.
To get a SharePoint token you will need to register an App in SharePoint itself or use the users username + password if available in your app.
Also see:
https://spshell.blogspot.com/2015/03/sharepoint-online-o365-oauth.html
https://shareyourpoint.net/2017/01/25/operations-using-rest-in-sharepoint-online-authorization/
For Graph, use an URL like this to get your list items:
https://graph.microsoft.com/v1.0/sites/{site-id}/lists/{list-id}/items?expand=fields(select=Column1,Column2)
You will probably need to do several calls to get your site ID and list ID first.
https://learn.microsoft.com/en-us/graph/api/listitem-list?view=graph-rest-1.0

Loopj Post method failure - error while trying to send post JSON

I am working in an android application that has to send user email through post method. The api endpoint is at https://api-iddog.idwall.co/ when i already run some tests and was able to GET values from here. Im using Loopj Library.
However, i've been tasked with using this endpoint:
https://api-iddog.idwall.co/signup
The documentation guide shows that i need to construct the POST method using the following parameters:
using Content-Type: application/json header
and the post URL should be something like:
Api Post Doc
With all that in mind, i got the create a method called attempPost(). On this method im creating the AsyncHttpRequest object, RequestParams object and storing the valid e-mail typed by the user.
private void attempPost() {
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
String url = "https://api-iddog.idwall.co/signup";
String userEmail = userEmailView.getText().toString();
JSONObject jsonEmail = new JSONObject();
try {
jsonEmail.put("email", userEmail);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("Dog", " " + jsonEmail.toString());
params.put("-d", jsonEmail);
client.addHeader("Content-Type", "application/json");
client.post(url, params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Log.d("Dog", "onSucess" + responseBody.toString());
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.e("Dog", "" + error.toString());
}
});
}
This method is called in a OnclickListener, and the log is returning a message called BadRequest and Status Code 400. I already tried to apply some code examples from Loopj doc but i didnt work. Can someone give me an insight in what i am doing wrong ? From what i can gather the success response should be a String(Token) and i need this token to complete the project.
EDIT.
I worked a little more through documentation and other examples here on Stack and i found this: POSTing JSON/XML using android-async-http (loopj)
In the accepted answer there is an example on how to post JSON.
Then i made a few changes in my attempPost method.
private void attempPost() {
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
String url = "https://api-iddog.idwall.co/signup";
String userEmail = userEmailView.getText().toString();
JSONObject jsonParams = new JSONObject();
try {
jsonParams.put("email", "your#email.com");
} catch (JSONException e) {
e.printStackTrace();
}
client.post(getApplicationContext(), url, jsonParams, "application/json", new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Log.d("Dog", "onSucess" + responseBody.toString());
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.e("Dog", "" + error.toString());
Log.e("Dog", "status code " + String.valueOf(statusCode));
}
});
}
But Android Studio is telling me to convert jsonParams into a entity. In the example i got from stack its uses the following code to achieve that:
StringEntity entity = new StringEntity(jsonParams.toString());
However my android studio gets an horror that says:
Unhandled exception : java.io.UnsupportedEncodingException,
Until this moment i could not figure a way to solve this.
I managed to make it work, the API its now returning a proper response and status code 200. I converted the JsonObject into a ByteArrayEntity since the StringEntity was not an option.
private void attempPost() {
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
String userEmail = userEmailView.getText().toString();
JSONObject jsonParams = new JSONObject();
try {
jsonParams.put("email", userEmail);
} catch (JSONException e) {
e.printStackTrace();
}
ByteArrayEntity be = new ByteArrayEntity(jsonParams.toString().getBytes());
//TODO create a class to handle JSON post, getmethods and parse token value
client.post(getApplicationContext(), API_URL, be, "application/json", new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
Log.d("Dog", "onSucess " + response.toString());
Log.d("Dog", "status code " + String.valueOf(statusCode));
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
super.onFailure(statusCode, headers, throwable, errorResponse);
Log.e("Dog", "" + errorResponse.toString());
Log.e("Dog", "status code " + String.valueOf(statusCode));
}
});
}

How to send authenticated request to Discogs Api

I'm following the OAuth 1.0 Protocol so I can send an Authenticated Request to /oauth/identity Endpoint as in step 5 of the Auth flow.
From the doc, making request involves including several params as you can see here.
What my requests looks like is :
http://api.discogs.com/oauth/identity?
oauth_consumer_key=CONSUMER_KEY&
oauth_nonce=1453720099377&
oauth_signature=CONSUMER_SECRET&ACCESS_TOKEN_SECRET&
oauth_signature_method=PLAINTEXT&
oauth_timestamp=1453720099377&
oauth_token=ACCESS_TOKEN
where ACCESS_TOKEN and ACCESS_TOKEN_SECRET derive from step 4 of the Auth Flow guide and
CONSUMER_SECRET and CONSUMER_KEY from my Discogs developer settings.
What my code looks in Java, since this is for an android Discogs client :
public void getIdentity() {
httpClient.addHeader("Content-Type", "application/x-www-form-urlencoded");
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("OAuth oauth_consumer_key=\"").append(Constants.CONSUMER_KEY).append("\",");
stringBuilder.append("oauth_nonce=\"").append(String.valueOf(System.currentTimeMillis())).append("\",");
stringBuilder.append("oauth_signature=\"").append(Constants.CONSUMER_SECRET).append(authAccessSecretToken).append("\",");
stringBuilder.append("oauth_signature_method=\"PLAINTEXT\",");
stringBuilder.append("oauth_timestamp=\"").append(String.valueOf(System.currentTimeMillis())).append("\",");
stringBuilder.append("oauth_token=\"").append(authAccessToken).append("\"");
httpClient.addHeader("Authorization", stringBuilder.toString());
httpClient.addHeader("User-Agent", "Discs/1.0 +https://jb.com");
httpClient.get(identityURL, null, new TextHttpResponseHandler() {
#Override
public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
Log.d(TAG, "onFailure IDENTITY " + i + " Throwable = " + throwable);
Log.d(TAG, "onFailure IDENTITY " + s);
}
#Override
public void onSuccess(int i, Header[] headers, String s) {
Log.i(TAG, "onSuccess IDENTITY -- String= " + s);
}
});
}
But what I get is : {"message": "You must authenticate to access this resource."}
Using an OAuth library instead of generating these requests manually will likely save you a headache. more information read https://www.rfc-editor.org/rfc/rfc5849#page-14

byte[] to string return null Android

i spend a lot of time to search how resolve my problem but stil unsuccessful, so i hop some one could help me.
I make my app with android studio:
i finish my page with login and httm request (100% working to conect and creat new account) and now i trying to make Get request to my server and get username rerver turn my array of bytes that i try to cast on string and in obtain just null "".
there is my code:
mainActivity.java
Button b = (Button)findViewById(R.id.b2);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SyncHttpClient client = new SyncHttpClient();
RequestParams params = new RequestParams();
params.put("email", "test3#t.com");
// Handle request
client.get("https://......../user/get/", params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
// called when response HTTP status is "200 OK"
System.out.println("response ----" + response);
String res = new String(response); //convetion Byte[] to String that i use
Context context = getApplicationContext();
Toast.makeText(context, res, Toast.LENGTH_SHORT).show();
System.out.println("res ----" + res);
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
System.out.println("errorResponse -----"+errorResponse);
String res = new String(errorResponse);
Context context = getApplicationContext();
// Toast.makeText(context, res, ast.LENGTH_SHORT).show();
System.out.println("ERROR--" + res);
}
});
}});
Server side it's look like this :
views.py
def get_users(req):
"""
Use url :
https://...../user/get/
With arguments :
?email=EMAIL
"""
email = req.GET.get('email')
if email is not None:
exists = User.objects.filter(email=email)
if len(exists) == 0:
return HttpResponse("Error invalid email !")
else:
res = "%s:%s" %(exists[0].username, exists[0].points)
return HttpResponse(exists[0].username)
else:
return HttpResponse("Missing information !")
And that what i obtain on Android Monitor:
I/System.out: response------[B#4136b800
I/System.out: res --------
ass you can see after covertion i have just NULL .
Can Someone help me plz

Categories