I am developing simple Android app where I am using google spreadsheet as a data source. For communication I am using google app script which implements doPost method because my app is sending some data to sheet and also wants some data as a response. The problem is instead of json response I always get html response about redirection in the errorBody().
I have also set OkHttpClient with redirections enabled to my retrofit service, but result is still the same.
I am working with Insomnia rest client for debugging and when I set redirections on there, everything works there fine.
If somebody had the same problem and solved it, please help.
Edit:
Here is my code:
public class Connector {
private static final String BASE_URL = "https://script.googleusercontent.com/";
private static final Object LOCK = new Object();
private static CallTaxiService service;
private static final String TAG = "Connector";
private static CallTaxiService getService()
{
if (service == null)
{
synchronized(LOCK) {
Log.d(TAG, "creating instance");
service = buildService();
}
}
return service;
}
private static CallTaxiService buildService()
{
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(new OkHttpClient.Builder().followRedirects(true)
.followSslRedirects(true).build())
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit.create(CallTaxiService.class);
}
public static void syncData(List<TaxiServiceAppData> data, Callback<Response> callback)
{
Call<Response> call = getService().sendData(data);
Log.d(TAG, "syncing data");
call.enqueue(callback);
}
private interface CallTaxiService {
#Headers({"Content-type: application/json"})
#POST("endpoint_url")
Call<Response> sendData(#Body List<TaxiServiceAppData> data);
}
}
And here is how I am calling it:
Connector.syncData(taxiServiceAppData, new retrofit2.Callback<com.adrisoft.calltaxi.model.Response>() {
#Override
public void onResponse(Call<com.adrisoft.calltaxi.model.Response> call, Response<com.adrisoft.calltaxi.model.Response> response) {
com.adrisoft.calltaxi.model.Response data = response.body();
if (data != null) {
newCities = data.getCities();
newTaxis = data.getTaxis();
updateDb();
prefs.saveSyncTime();
isSyncRunning = false;
callback.onSuccess();
} else {
try {
Log.d(TAG, "Sync failed ... no data available. Error: " + response.errorBody().string());
} catch (Exception ex) {
}
callback.onFailure();
}
}
#Override
public void onFailure(Call<com.adrisoft.calltaxi.model.Response> call, Throwable t) {
Log.d(TAG, "Sync request failed.");
isSyncRunning = false;
callback.onFailure();
}
});
And exactly in the log "Sync failed ... no data available ..." I am getting this from errorBody():
<HTML>
<HEAD>
<TITLE>Temporary Redirect</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Temporary Redirect</H1>
The document has moved here.
</BODY>
</HTML>
Redirect could have happened because the server endpoint provided https and in your code you call http. Then the server would redirect to https. Only GET requests can be redirected, so others like POST will result in error.
Related
I've tried making a retrofit call to an API endpoint, but it's returning a 400 error, however my curl request is working perfectly fine. I can't seem to spot the error, could someone double check my work to see where I made a mistake?
The curl call that works:
curl --request POST https://connect.squareupsandbox.com/v2/payments \
--header "Content-Type: application/json" \
--header "Authorization: Bearer accesstoken112233" \
--header "Accept: application/json" \
--data '{
"idempotency_key": "ab2a118d-53e2-47c6-88e2-8c48cb09bf9b",
"amount_money": {
"amount": 100,
"currency": "USD"},
"source_id": "cnon:CBASEITjGLBON1y5od2lsdxSPxQ"}'
My Retrofit call:
public interface IMakePayment {
#Headers({
"Accept: application/json",
"Content-Type: application/json",
"Authorization: Bearer accesstoken112233"
})
#POST(".")
Call<Void> listRepos(#Body DataDto dataDto);
}
DataDto class:
public class DataDto {
private String idempotency_key;
private String amount_money;
private String source_id;
public DataDto(String idempotency_key, String amount_money, String source_id) {
this.idempotency_key = idempotency_key;
this.amount_money = amount_money;
this.source_id = source_id;
}
}
And lastly making the retrofit call:
DataDto dataDto = new DataDto("ab2a118d-53e2-47c6-88e2-8c48cb09bf9b", "{\"amount\": 100, \"currency\": \"USD\"}", "cnon:CBASEITjGLBON1y5od2lsdxSPxQ");
RetrofitInterfaces.IMakePayment service = RetrofitClientInstance.getRetrofitInstance().create(RetrofitInterfaces.IMakePayment.class);
Call<Void> call = service.listRepos(dataDto);
call.enqueue(new Callback<Void>() {
#Override
public void onResponse(#NonNull Call<Void> call, #NonNull Response<Void> response) {
Log.d(TAG, "onResponse: " + response.toString());
}
#Override
public void onFailure(#NonNull Call<Void> call, #NonNull Throwable t) {
Log.d(TAG, "onFailure: Error: " + t);
}
});
Retrofit Instance:
public class RetrofitClientInstance {
private static Retrofit retrofit;
private static final String BASE_URL = "https://connect.squareupsandbox.com/v2/payments/";
public static Retrofit getRetrofitInstance() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
Edit 1: Changing to second parameter to JSON Object
JSONObject jsonObject = new JSONObject();
try{
jsonObject.put("amount", 100);
jsonObject.put("currency", "USD");
}catch (Exception e){
Log.d(TAG, "onCreate: " + e);
}
DataDto dataDto = new DataDto("ab2a118d-53e2-47c6-88e2-8c48cb09bf9b", jsonObject, "cnon:CBASEITjGLBON1y5od2lsdxSPxQ");
First of all, let's see what 400 means
The HyperText Transfer Protocol (HTTP) 400 Bad Request response status
code indicates that the server cannot or will not process the request
due to something that is perceived to be a client error (e.g.,
malformed request syntax, invalid request message framing, or
deceptive request routing).
Now we are sure, the problem stands in our request (not server fault), most probably it is because you are trying to convert JSON in request (do not do this explicitly GSON will convert automatically)
Use interceptor to verify your outgoing network requests (Tell the result here)
you use #POST(".") which does not make sense, please understand BASE_URL is your server URL NOT MORE
The problem could be translating this post request
So a possible solution
Change base URL into "https://connect.squareupsandbox.com/"
Replace #POST(".") with #POST("v2/payments/")
PS. #NaveenNiraula mentioned right thing even though it did not help you, please follow his instruction, it is the correct way parsing data using GSON (make sure you include it and configure it correctly) converter
EDIT
I make it work (I eliminated 400 error code that is what you want as long as question title is concerned) partially which means I detect why 400 error was occurred and fixed it but unfortunately, I stuck the UNAUTHORIZED issue. The problem was relating to converting json and data type
data class DataDTO(
val idempotency_key: String,
val source_id: String,
val amount_money: MoneyAmount
)
data class MoneyAmount(
val amount: Int,
val currency: String
)
I gist all code here you can refer
You need two DTO classes as below:
public class Amount_money
{
private String amount;
private String currency;
public String getAmount ()
{
return amount;
}
public void setAmount (String amount)
{
this.amount = amount;
}
public String getCurrency ()
{
return currency;
}
public void setCurrency (String currency)
{
this.currency = currency;
}
#Override
public String toString()
{
return "ClassPojo [amount = "+amount+", currency = "+currency+"]";
}
}
And
public class DataDto
{
private String idempotency_key;
private Amount_money amount_money;
private String source_id;
public String getIdempotency_key ()
{
return idempotency_key;
}
public void setIdempotency_key (String idempotency_key)
{
this.idempotency_key = idempotency_key;
}
public Amount_money getAmount_money ()
{
return amount_money;
}
public void setAmount_money (Amount_money amount_money)
{
this.amount_money = amount_money;
}
public String getSource_id ()
{
return source_id;
}
public void setSource_id (String source_id)
{
this.source_id = source_id;
}
#Override
public String toString()
{
return "ClassPojo [idempotency_key = "+idempotency_key+", amount_money = "+amount_money+", source_id = "+source_id+"]";
}
}
You need to create object for each like under :
Amount_money am = new Amount_money();
am.setAmount("100");
am.setCurrency("USD");
DataDto dto = new DataDto();
dto.setIdempotency_key("your key");
dto.setsource_id("your id");
dto.setAmount_money(am);
RetrofitInterfaces.IMakePayment service = RetrofitClientInstance.getRetrofitInstance().create(RetrofitInterfaces.IMakePayment.class);
Call<Void> call = service.listRepos(dataDto);
// yo get the point follow along
Most likely the passed JSON structure is not serialized in the same format.
"amount_money": {
"amount": 100,
"currency": "USD"},
I would at first use for private String amount_money; a real DTO having the amount and currency fields. This should give progress. I'm not 100% sure how the underscore mapping of attributes looks like, but this is the next step.
Add logging to be able to see the passed data. A quick search reveals this tutorial: https://futurestud.io/tutorials/retrofit-2-log-requests-and-responses. When seeing the transmitted data it should be easy to compare the expected and sent data.
Please check your base url.
In your curl you have https://connect.squareupsandbox.com/v2/payments
But in the code you have
private static final String BASE_URL = "https://connect.squareupsandbox.com/v2/payments/";
There is extra / (slash) in the end. I've seen cases where it was the issue. Could be your problem :)
I am trying to send data (POST request) from android app using retrofit2 library and receive it on the server which is written in nodejs (using express framework) but i am not able to retrieve the data which is sent from the the app.
I used retrofit with GsonConverterfactory and sent a POST request to "/temp" route.
Index.js (handles route requests):-
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.urlencoded({extended:true}));
app.use('/public',express.static('public'));
app.post("/temp",function(req,res){
console.log(req.body);
obj = {
orgName : "Got the message ",
address : "on the server"
}
res.json(obj);
})
app.listen(8000,function(){
console.log("Server Started at port 8000");
})
Shop.java
package com.example.myapplication;
public class Shop {
private String orgName;
private String address;
public Shop(String orgName, String address) {
this.orgName = orgName;
this.address = address;
}
public String getOrgName() {
return orgName;
}
public String getAddress() {
return address;
}
}
ShopApi.java
package com.example.myapplication;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.POST;
public interface ShopApi {
#POST("temp")
Call<Shop> create(#Body Shop shop);
}
postData() - Method to post data from MainActivity.java
public void postData(View view){
String BASE_URL = "http://10.0.2.2:8000/";
String org = orgName.getText().toString();
String address = add.getText().toString();
//Toast.makeText(getApplicationContext(),org+" "+address,Toast.LENGTH_SHORT).show();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
ShopApi shopApi = retrofit.create(ShopApi.class);
Shop shop = new Shop(org,address);
Call<Shop> shopCall = shopApi.create(shop);
shopCall.enqueue(new Callback<Shop>() {
#Override
public void onResponse(Call<Shop> call, Response<Shop> response) {
if(!response.isSuccessful()){
Toast.makeText(getApplicationContext(),response.code(),Toast.LENGTH_LONG).show();
}
Shop shopResponse = response.body();
String content = shopResponse.getOrgName() + shopResponse.getAddress();
Toast.makeText(getApplicationContext(),content,Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<Shop> call, Throwable t) {
Toast.makeText(getApplicationContext(),t.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
A json object is expected in the req.body which should be printed in terminal but this gets printed :-
Server Started at port 8000
{}
Please help me to retrieve data on sever.
I don't work in Node.js still I try to answer your question.
You're expecting a JSON object in server like below,
{
"orgName": "Organization name",
"address": "Organization address"
}
Okay, your Android part (Retrofit api interface) is correct. In run-time it produces the expected JSON object. But, in your server side you're accepting application/x-www-form-urlencoded instead of application/json data. Which is causing this issue IMO.
Just replace the following code from
app.use(bodyParser.urlencoded({extended:true}));
to
app.use(bodyParser.json());
And give it a try once!
body-parser doc
Actually i'm trying to post a text file to my server and i would be able to handle the error when i've sent the file but i didn't get the response (In case the file has been sent the network is gone down so the server received the file but the device don't know it)
Because for now i'm getting an issue because if i don't get the response when the device return online it send again the same file and i would prevent it.
Seems it's hidely retry to send the file on connection fail or something like that.
Here is my method which i use onClick to send the file:
public void sendPost() {
#SuppressLint({"SdCardPath", "DefaultLocale"}) final File file = new File("/data/data/com.example.igardini.visualposmobile/files/"+String.format("%03d", Integer.valueOf(nTerminalino))+"_"+nTavoli.getText().toString()+".txt");
final MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);
final RequestBody fbody = RequestBody.create(MediaType.parse("text/*"), file);
builder.addFormDataPart(String.format("%03d", Integer.valueOf(nTerminalino))+"_"+nTavoli.getText().toString(), file.getName(),fbody);
final MultipartBody requestBody = builder.build();
final APIService apiService = ApiUtils.getAPIService(ipCASSA);
final Call<Void> calls = apiService.savePost(requestBody);
calls.enqueue(new Callback<Void>() {
#Override
public void onResponse(#NonNull Call<Void> call, #NonNull Response<Void> response) {
if (response.isSuccessful()) {
Log.i("RESPONSE: ", response.toString());
Print();
dialogLoading.dismiss();
Runtime.getRuntime().gc();
// checkFile task = new checkFile();
// task.execute();
}else {
Toast.makeText(pterm.this,"ERRORE",Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(#NonNull Call<Void> call, #NonNull Throwable t) {
if(t instanceof IOException) {
Log.e("TAG", t.toString());
MediaPlayer mpFound = MediaPlayer.create(pterm.this, R.raw.errorsound);
mpFound.start();
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
if (v.hasVibrator()) {
v.vibrate(6000);
}
new GlideToast.makeToast(pterm.this, "CONNESSIONE FALLITA!", GlideToast.LENGTHLONG, GlideToast.FAILTOAST).show();
dialogLoading.dismiss();
}
}
});
}
While here are my other useful classes:
class ApiUtils {
private ApiUtils() {}
static APIService getAPIService(String ipCASSA) {
String BASE_URL = "http://"+ipCASSA+"/web/";
final OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(10000, TimeUnit.MILLISECONDS)
.writeTimeout(10000, TimeUnit.MILLISECONDS)
.readTimeout(10000, TimeUnit.MILLISECONDS)
.retryOnConnectionFailure(false)
.build();
return RetrofitClient.getClient(BASE_URL,okHttpClient).create(APIService.class);
}
}
public interface APIService {
#POST("CART=PTERM")
Call<Void> savePost(#Body RequestBody text);
}
class RetrofitClient {
private static Retrofit retrofit = null;
static Retrofit getClient(String baseUrl, OkHttpClient okHttpClient) {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
In that case I would add to file some sort of device generated random ID, and send it along with request.
On server side I would change logic to first try to locate file in DB using this ID, if there is none, store it and return status OK along with maybe server side id (might come handy later).
If there is file with ID provided on request, just return server side ID with status 200 - that way you will not store it twice.
You can even go further - if you have not stable connection (it seems like it from description) you could even make seperate REST call to check if file is on server side by generated id or checksum, and if not then start to send it - it will safe bandwitch.
It does not have to be generated ID - it can be checksum of a file for example. Whatever is easier for you.
For generating ID you could use Android's UUID
https://developer.android.com/reference/java/util/UUID
For checksum check this answer:
How to generate an MD5 checksum for a file in Android?
BTW - I would not do 10 seconds timeout limit - it is way too much, and user experience will be terrible
I am using retrofit to pass login and register api in android. But I am getting response as 409 in return. I am not getting data from api. Retrofit 2 is used here
SignUpApi signupapi = Api_Config.getInstance3().getApiBuilder().create(SignUpApi.class);
Call<SignUpApi.ResponseSignUp> call = signupapi.POSTDATA(UserName.getText().toString().trim(),
Email.getText().toString().trim(),
Password.getText().toString().trim(),
Sex.getText().toString().trim(),
Mobile.getText().toString().trim());
call.enqueue(new Callback<SignUpApi.ResponseSignUp>() {
#Override
public void onResponse(Call<SignUpApi.ResponseSignUp> call, Response<SignUpApi.ResponseSignUp> response) {
CustomProgressDialog.getInstance().dismiss();
if (response.isSuccessful()){
Log.e("Status is",response.body().getStatus().toString());
if (response.body().getStatus() == 200){
CommonFunctions.getInstance().ShowSnackBar(SignInActivity.this,Constants.SuccessfullyRegistered);
CommonFunctions.getInstance().FinishActivityWithDelay(SignInActivity.this);
}else if (response.body().getStatus() == 409){
CommonFunctions.getInstance().ShowSnackBar(SignInActivity.this,Constants.YouAreAlreadyRegistered);
}else{
CommonFunctions.getInstance().ShowSnackBar(SignInActivity.this,response.body().getMsg());
}
} else {
CommonFunctions.getInstance().ShowSnackBar(SignInActivity.this,Constants.SomethingWentWrong);
}
}
#Override
public void onFailure(Call<SignUpApi.ResponseSignUp> call, Throwable t) {
CustomProgressDialog.getInstance().dismiss();
CommonFunctions.getInstance().ShowSnackBar(SignInActivity.this,t.getMessage());
}
});
}
Below is my API configuration
public static Api_Config getInstance3()
{
if (ourInstance == null){
synchronized (Api_Config.class){
if ( ourInstance == null )
ourInstance = new Api_Config();
}
}
ourInstance.config3();
return ourInstance;
}
private void config3() {
Gson gson = new GsonBuilder()
.setLenient()
.create();
String BASE_URL3 = LOGIN_AND_SIGNUP;
mRetrofit = new Retrofit.Builder()
.baseUrl(BASE_URL3)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
Below is my Api Class
public interface SignUpApi {
#FormUrlEncoded
#POST("register.php")
Call<ResponseSignUp> POSTDATA(#Field("user_name")String username,
#Field("user_email")String email,
#Field("user_password")String password,
#Field("user_gender")String sex,
#Field("user_mobile")String mobile
);
public class ResponseSignUp
{
#SerializedName("status")
#Expose
private Integer status;
#SerializedName("msg")
#Expose
private String msg;
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
I am newbee to android and really confused why my code is not working. Looking for help. Thanks in Advance
Note that if your response was successfully it means you got a successful code (200...300). However, if you get a response 401, 409.. it means you got an error, then your response was not successfully. Put the error handle outside the response.isSuccessful() condition.
if (response.isSuccessful()){
//Handle success response here
Log.e("Status is",response.body().getStatus().toString());
CommonFunctions.getInstance().ShowSnackBar(SignInActivity.this,Constants.SuccessfullyRegistered);
CommonFunctions.getInstance().FinishActivityWithDelay(SignInActivity.this);
} else {
// Handle error response here, 401, 409...
if (response.body().getStatus() == 409){
CommonFunctions.getInstance().ShowSnackBar(SignInActivity.this,Constants.YouAreAlreadyRegistered);
}else{
CommonFunctions.getInstance().ShowSnackBar(SignInActivity.this,response.body().getMsg());
}
}
You can check this in the retrofit2 files.
/** Returns true if {#link #code()} is in the range [200..300). */
public boolean isSuccessful() {
return rawResponse.isSuccessful();
}
EDIT
Depper explanation
I'll try to explain better. When you call retrofit using enqueue method like this: call.enqueue() you expect to get a Response or Failure from the server: onResponse() means you got a response and onFailure() means you failed to connect to the server, it could mean the server is broken or there is no internet connection.
If you got a onResponse() from the server it does not mean it was successful, it just means you got a response, therefore you need to check if this response was successful or not by using this condition
if (response.isSuccessful){
}
What is a successful response?
If you end up inside this condition response.isSuccessful it already means you got a successful response and this is a response with code between 200 and 300.
However, if you want to check if you got a 409 code. 409 code means that it was a unsuccessful response, then you need to check this outside the success condition.
if (response.isSuccessful){
// You got a successful response, the code is from 200 to 300.
} else {
// You got a unsuccessful response, handle the code 401, 405, 409 here.
}
I have an app connected with Azure backend. I created a login and some api calls 2 months ago. They worked fine until a few days ago and then it starts to fail "sometimes".
The login log onFailure says: Error while authenticating user
The callback log onFailure says: Error while processing request
And the cause of both says : stream was reset: PROTOCOL_ERROR
This post is to similar to this but didn't work.
Some code here:
LoginFragment.java
private void login(String email, String password){
loginProgressBar.setVisibility(View.VISIBLE);
try {
JsonObject params = new JsonObject();
params.addProperty("Username", email);
params.addProperty("Password", password);
ListenableFuture<MobileServiceUser> listenable = Client.logIn(getContext(), params);
Futures.addCallback(listenable, new FutureCallback<MobileServiceUser>() {
#Override
public void onSuccess(MobileServiceUser mobileServiceUser) {
loginProgressBar.setVisibility(View.GONE);
SharedPreferences settings = getActivity().getSharedPreferences(Client.MS_USER,0);
SharedPreferences.Editor editor = settings.edit();
Client.clientId = mobileServiceUser.getUserId();
Client.token = mobileServiceUser.getAuthenticationToken();
editor.putString(Client.MS_USER_ID, Client.clientId);
editor.putString(Client.MS_AUTH_TOKEN, Client.token);
editor.apply();
Client.getInstance(getContext()).setCurrentUser(mobileServiceUser);
Intent i = new Intent(getContext(), MainActivity.class);
startActivity(i);
}
#Override
public void onFailure(Throwable t) {
loginProgressBar.setVisibility(View.GONE);
Throwable t2 = t.getCause();
Throwable t3 = t2.getCause();
Log.e("LoginFail", t.getMessage());
Log.e("LoginFail", t2.getMessage());
if(t3 != null){
Log.e("LoginFail", t3.getMessage());
}
Toast.makeText(getContext(), getResources().getString(R.string.bad_login), Toast.LENGTH_LONG).show();
}
}, MoreExecutors.directExecutor());
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
Client.java
public class Client {
public static final String MS_USER = "MS_USER";
public static final String MS_USER_ID = "MS_USER_ID";
public static final String MS_AUTH_TOKEN = "MS_AUTH_TOKEN";
public static String clientId;
public static String token;
private static MobileServiceClient instance = null;
public static MobileServiceClient getInstance(Context context) {
if (instance ==null){
try {
instance = new MobileServiceClient(Env.AZURE_URL, context);
instance.setAndroidHttpClientFactory(() -> {
OkHttpClient client = new OkHttpClient();
client.setReadTimeout(20, TimeUnit.SECONDS);
client.setWriteTimeout(20, TimeUnit.SECONDS);
return client;
});
} catch (MalformedURLException e) {
e.printStackTrace();
}
} else{
instance.setContext(context);
}
return instance;
}
public static ListenableFuture<MobileServiceUser> logIn(Context context, JsonObject parameters) throws MalformedURLException {
String deviceID = "gcm:" + Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
parameters.addProperty("device_id", deviceID);
parameters.addProperty("device_dateTime", Env.DATE_FORMAT.format(new Date()));
parameters.addProperty("device_timeZone", API.getTimezone());
parameters.addProperty("device_language", Env.LANGUAGE);
parameters.addProperty("app", Env.APP_NAME);
return getInstance(context).login("auth", parameters);
}
public static ListenableFuture<JsonElement> callApi(Context context, String apiName, JsonObject parameters, String httpMethod){
if(httpMethod.equals("POST")){
String deviceID = "gcm:" + Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
parameters.addProperty("user_id", Client.clientId);
parameters.addProperty("device_id", deviceID);
parameters.addProperty("device_dateTime", Env.DATE_FORMAT.format(new Date()));
parameters.addProperty("device_timeZone", API.getTimezone());
parameters.addProperty("device_language", Env.LANGUAGE);
parameters.addProperty("app", Env.APP_NAME);
parameters.addProperty("role", "Patient");
return getInstance(context).invokeApi(apiName, parameters, httpMethod, null);
} else {
return getInstance(context).invokeApi(apiName, null, httpMethod, null);
}
}
This is probably related to an issue in Azure App Service that is weirdly enough not reported on the public Azure status page.
The message that affected Azure client received was (quoted from the link above):
Starting at 02:00 UTC on 3 Apr 2018, you have been identified as a
customer using App Services who may have received connection failure
notifications when using Android apps with older HTTP clients or
desktop browsers using cross-site scripting calls. Engineers have
identified an issue with a recent deployment and are investigating
mitigation options. Customers experiencing this issue can
self-mitigate by updating the site config setting "http20Enabled" to
false via resources.azure.com. Instructions on how to update site
config can be found here:
https://azure.microsoft.com/en-us/blog/azure-resource-explorer-a-new-tool-to-discover-the-azure-api/
Go to https://resources.azure.com/
Make sure you are in Read/Write mode by clicking in the option to the
left of your name.
Find the affected site and browse to Config > Web:
https://resources.azure.com/subscriptions//resourceGroups//providers/Microsoft.Web/sites//config/web
Change the property: "http20Enabled": from true to false by clicking
in Edit properties, Update to “false” and then clicking PUT to save
change.
If you have tried these steps and are continuing to experience issues
with your App Service, please create a technical support ticket to
further troubleshoot: aka.ms/azsupt. This message will be closed in 7
days.