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());
}
});
}
Related
I've created an Android app (Java) that uses Microsoft Graph Mail API to read and delete messages (emails). Reading messages works, but deleting results in this error
com.microsoft.graph.core.ClientException: Error during http request
Reading messages (runs successfully):
final String accessToken = authenticationResult.getAccessToken();
IGraphServiceClient graphClient =
GraphServiceClient
.builder()
.authenticationProvider(new IAuthenticationProvider() {
#Override
public void authenticateRequest(IHttpRequest request) {
Log.d(TAG, "Authenticating request," + request.getRequestUrl());
request.addHeader("Authorization", "Bearer " + accessToken);
}
})
.buildClient();
graphClient
.me()
.messages()
.buildRequest()
.select("id, subject, body, from")
.top(50)
.get(new ICallback<IMessageCollectionPage>() {
#Override
public void success(IMessageCollectionPage iMessageCollectionPage) {
displayGraphResult(iMessageCollectionPage.getRawObject());
}
#Override
public void failure(ClientException ex) {
displayError(ex);
}
});
Here's the API call to delete a message:
graphClient
.me()
.messages(graph_id)
.buildRequest()
.delete(new ICallback<Message>() {
#Override
public void success(Message message) {
Log.d("DeleteAPI", "Successfully deleted!");
}
#Override
public void failure(ClientException ex) {
Log.d("DeleteAPIError", ex.toString());
displayError(ex);
}
});
Thanks!
Yikes. When I extracted the graph_id from the get request it was surrounded by quotations. I removed the quotations and now the delete call is working properly
I´m trying to get data from my api. In postman the request works, here´s the response:
{
"ips_Beacons_BeaconID": 14,
"ips_Beacons_BeaconDescription": "b2",
"ips_Beacons_BeaconLat": 12.3123,
"ips_Beacons_BeaconLon": 32.123,
"ips_Beacons_BeaconImgX": 45,
"ips_Beacons_BeaconImgY": 123
}
I´ve tried and i got the response with Okhttp. However it stopped working for some reason.
Although i got the response, i wish to serialize the json string it and instanciate objects. But i couldn´t get the response out of the onSuccess method inside the callback.
This is what i had that workd but doens´t work anymore:
OkHttpClient client = new OkHttpClient();
String url ="http://192.168.1.95:44374/api/beacons";
Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) { e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()){
String myResponse = response.body().string();
listBeacons = objectMapper.readValue(myResponse, new TypeReference<List<Beacon>>(){});
Log.i(TAG, myResponse);
}
}
});
I need the listBeacons List to perform other operations outside this activity.
I am trying to get the responce from the server but it is returinig 403 forbidden but testing api on apitester.com works.
This is the code how i am reqesting the get method :
public void getResponse(Context context) throws IOException {
OkHttpClient client = new OkHttpClient();
Hmac hmac = new Hmac();
String auth = hmac.txt;
String url = "https://api.hotstar.com/h/v1/play?contentId=1000034502";
Request request = new Request.Builder()
.url(url)
.addHeader("hotstarauth",auth)
.addHeader("referer","https://hotstar.com/movies/2-states/1000034502")
.addHeader("x-country-code","IN")
.addHeader("x-platform-code","TABLET")
.addHeader("x-region-code","undefined")
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
Toast.makeText(context, "Error Occured", Toast.LENGTH_SHORT).show();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
Log.d("Server Responded: ", response.toString());
}
});
}
and in response i am getting 403 FORBIDDEN
but using the same config on apitester.com it works !
here is the sharedconig on apitester https://www.apitester.com/shared/checks/dca814bb92fb40af8aecda95cdf2f39c
why i am not getting the response on android ?
I'm using com.squareup.retrofit2:retrofit:2.2.0
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(logging);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://localhost:9000")
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient.build())
.build();
final UserService service = retrofit.create(UserService.class);
Call<User> userCall = service.createUser(user)
Here is the problem: when I run the execute it make REST API request but when I use enqueue it does nothing (no exception, no log)
userCall.execute(); //this work
//this does not work
userCall.enqueue(new Callback<User>() {
#Override
public void onResponse(Call<User> call, Response<User> response) {
// no response
}
#Override
public void onFailure(Call<User> call, Throwable t) {
//nothing here
}
});
Well,
The issue was because I was using an emulator and try to call the localhost however, it turn out if you want call the localhost you have to use this ip 10.0.2.2
The execute works because I was running as unit test but when it runs enqueue I think it need to run on android platform.
refer to this
https://developer.android.com/studio/run/emulator.html#networkaddresses
How to get the Android Emulator's IP address?
You can try this full Answer Link
Here is the shortest code snippest.
private void emailLoginRequest() {
LoginService loginService = ApiFactory.createService(LoginService.class);
Call<JsonObject> call = loginService.login(edtEmail.getText().toString(),edtPassword.getText().toString(),mDeviceType,mDeviceToken);
call.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
hideProgressDialog();
if (response.isSuccessful()) {
LOGD(TAG, "onResponse 0: " + response.body().toString());
LoginResponse loginResponse = new Gson().fromJson(response.body().toString(), LoginResponse.class);
System.out.println("+++ get message >> " + loginResponse.getMessage());
int status = loginResponse.getStatus();
}else {
LOGD(TAG, "response fail 0: " + response.body());
}
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
hideProgressDialog();
LOGD(TAG, "onFailure: " + t.getMessage());
}
});
}
put your code as this:
userCall.enqueue(new Callback<User>() {
#Override
public void onResponse(Call<User> call, Response<User> response) {
Toast.makeText(this, "in response", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<User> call, Throwable t) {
Toast.makeText(this, "in response", Toast.LENGTH_SHORT).show();
}
});
Now based on method call you will get toast if its in response toast will be "In response" don't forget write youractivity name before this like : MainActivity.this
see this
retrofit can be called by 2 methods separately one is synchronous and another way is asynchronous.
enqueue is an asynchronous way where it does not wait for a response and proceed. here you need to handle Call separately to load UI later.
Execute is asynchronously call rest api and wait until get response and process it.
choice wisely
I am using gwt with php.
I am trying to get data fom the http://typing.lc/userInfo.php url.
but the following code returns nothing, but response.getText() is 200, however when i ask http://typing.lc/userInfo.php through browser it returns value.
try
{
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, "http://typing.lc/userInfo.php");
builder.setHeader("Content-Type", "application/x-www-form-urlencoded");
builder.sendRequest("", new RequestCallback()
{
#Override
public void onError(Request request, Throwable exception)
{
Window.alert("Error");
}
#Override
public void onResponseReceived(Request request, Response response)
{
Window.alert("Success: " + response.getText());
}
});
}
catch (RequestException e)
{
Window.alert("Exception");
}
You are probably running into a SOP (Same Origin Policy) issue.
See here for possible solutions.