I have a json data to be sent using retrofit in android howerver it's not not getting sent to the server. I have used slim framework at the server side .
this is my interface in android client side
public interface RequestInterface
{
#Headers("Content-type: application/json")
#POST("/instituteRegister")
Call<InstRegServerResponse> sendInstRegData(#Body InstRegServerRequest
post);
}
this is the sign up method
> public void signup()
{
String regdName = _regdName.getText().toString();
String email = _email.getText().toString();
String password = _password.getText().toString();
Log.d("password", password);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RequestInterface requestInterface =
retrofit.create(RequestInterface.class);
InstRegServerRequest instRegServerRequest = new InstRegServerRequest();
instRegServerRequest.setiname(instituteName);
instRegServerRequest.setemail(email);
instRegServerRequest.setpassword(password);
Call<InstRegServerResponse> response =
requestInterface.sendInstRegData(instRegServerRequest);
response.enqueue(new Callback<InstRegServerResponse>()
{
#Override
public void onResponse(Call<InstRegServerResponse> call,
retrofit2.Response<InstRegServerResponse> response)
{
InstRegServerResponse resp = response.body();
Log.d("status:", "sign up success");
}
#Override
public void onFailure(Call<InstRegServerResponse> call, Throwable t)
{
Log.d(Constants.TAG,"signed up failed");
}
});
}
The error is the JSON data is not passed to the server
The api endpoint works correctly as i have tested it using postman
in the android logcat i get sign up success but at the server side I think the json is not passed correctly that's why i'm unable o write the data to the database
Try this.
#Headers("Content-Type: application/json; charset=UTF-8")
#POST("instituteRegister")
Call<InstRegServerResponse> sendInstRegData(#Body Map<String, Object> params);
Construct your JSON object using Map<String, Object>.
Example:
Map<String, Object> param = new HashMap<>();
param.put("YOUR_KEY", YOUR_VALUE);
Related
I try to call this Request with Retrofit
my code :
Map<String, String> parameters = new HashMap<>();
Clientn client = new Clientn();
final WaselJsonPlaceHolderApi apiService = client.getClient().create(WaselJsonPlaceHolderApi.class);
Call<TokenModel> call = apiService.getLoginToken( "password", "ec_user","EC_P#ssw0rd" , "0500344253", "1993");
call.enqueue(new Callback<TokenModel>() {
#Override
public void onResponse(Call<TokenModel> call, Response<TokenModel> response) {
Log.e("TAG-TAG", ""+response.errorBody());
Log.e("TAG-TAG", ""+response.body());
}
#Override
public void onFailure(Call<TokenModel> call, Throwable t) {
}
});
the Interface :
#FormUrlEncoded
#POST("api/CustomerAccount/LoginUserByMobile")
Call<TokenModel> getLoginToken( #Field("grant_type") String title,
#Field("app_username") String body,
#Field("app_password") String password,
#Field("mobile_number") String userId,
#Field("ver_code") String code );
the Client
public class Clientn {
public static final String BASE_URL = "http://192.168.1.230/MagicWord.ECommercPlatform.API/";
public static Retrofit retrofit = null;
public static Retrofit getClient(){
if (retrofit == null){
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
but i get the null response and the ErrorBody is E/TAG-TAG: okhttp3.ResponseBody$1#aa2472e
I think android stopped response for normal http in latest API(29), You can try with https and check the same issue is coming or not.
i think the issue is in your "ver_code which is int or use are taking string.is it string or int?
onFailure callback could be very useful, try to add t.printStacktrace() on it.
Also, don't pass an object as is with a string on Log, because it will just print an address that you don't need.
Keep field name and variable name same
Example:
#Field("grant_type") String grant_type, #Field("app_username") String app_username,#Field("app_password") app_password
so that you cannot get confused.
I think the request method should be POST
Because in code the request method is POST but in screenshot the request method is GET
I'm using Retrofit2 for the first time and have a few issues.
This is the code snippet used to call the REST API
//building retrofit object
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://192.168.0.71:9000/api/uniapp/")
.addConverterFactory(GsonConverterFactory.create())
.addConverterFactory(ScalarsConverterFactory.create())
.build();
APIService service = retrofit.create(APIService.class);
//defining the call
Call<String> call = service.refreshAppMetaConfig("0");
//calling the api
call.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
//displaying the message from the response as toast
System.out.println("Uniapp :"+response);
}
#Override
public void onFailure(Call<String> call, Throwable t) {
System.out.println("Uniapp :"+t.getMessage());
}
});
This is the APIService class :
public interface APIService {
//The register call
#FormUrlEncoded
#POST("appmetaconfigjson")
Call<String> refreshAppMetaConfig(#Field("versionId") String versionId);
}
I'm using Play framework for creating the REST API. I am getting an internal server error. The API is not able to read the JSON request. But if I hit the API through Postman, it returns the response. Any suggestions?
Ive added the postman request screenshot.
As I can see from your screenshots of Postman, you're sending JSON body to REST API. When you select body type as raw - application/json in Postman, it automatically includes
Content-Type:application/json
as header. Hence, the request is successful in Postman.
Now, in order to make it work above request successfully in your Android application, you need to set headers with the request you send to REST API.
In APIService interface do the below changes.
import retrofit2.http.Body;
import okhttp3.ResponseBody;
import java.util.Map;
public interface APIService {
//The register call
// #FormUrlEncoded <==== comment or remove this line
#Headers({
"Content-Type:application/json"
})
#POST("appmetaconfigjson")
Call<ResponseBody> refreshAppMetaConfig(#Body Map<String, String> versionId);
}
Remove or comment #FormUrlEncoded annotation as we're sending JSON not FormUrlEncoded data.
Add #Headers() annotation with Content-Type:application/json
Change method parameter to #Body Map<String, String> versionId. The #Body annotation converts (serializes) Map (HashMap) data into JSON body when you request to API.
Change return parameter from String to ResponseBody.
Use the above-modified method as below
// code...
//defining the call
// create parameter with HashMap
Map<String, String> params = new HashMap<>();
params.put("versionId", "0");
Call<ResponseBody> call = service.refreshAppMetaConfig(params);
//calling the api
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
//displaying the message from the response as toast
// convert ResponseBody data to String
String data = response.body().string();
System.out.println("Uniapp : " + data);
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
System.out.println("Uniapp : " + t.getMessage());
}
});
Here also you need to change parameter from Call<String> to Call<ResponseBody>. And convert the response inside onResponse() method using response.body().string();.
I need to get the XML file from the site. I'm learning to use Retrofit.
I need to make a request and attach my API key via the "X-AppId" header. It should look like this:
X-AppId: my key.
If I do this from the browser, I get the answer.
Through the retrofit I get the access
error 403 Forbidden code = 403, message = Forbidden, url = https: //
Tell me how it is implemented properly to receive an answer from the server code = 200
Here is my implementation:
public interface myAPIinterface {
#GET("/api/ru/index/route/?from=Minsk&to=Warsaw")
Call<Routes> getProducts();
}
This is the activity where I output to the log:
private void getProducts(){
final ProgressDialog loading = ProgressDialog.show(this,"Fetching Data","Please wait...",false,false);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
Log.d(TAG, "getProducts");
httpClient.addInterceptor(new Interceptor() {
#Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request()
.newBuilder()
.addHeader("X-AppId:", "97377f7b702d7198e47a2bf12eec74")
.build();
return chain.proceed(request);
}
});
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://rasp.rw.by")
.addConverterFactory(SimpleXmlConverterFactory.create())
.build();
myAPIinterface api = retrofit.create(myAPIinterface.class);
Call<Routes> call = api.getProducts();
call.enqueue(new Callback<Routes>() {
#Override
public void onResponse(#NonNull Call<Routes> call, #NonNull Response<Routes> response) {
Log.d(TAG, "onResponse");
Log.d(TAG, String.valueOf(kk));
Log.d(TAG, String.valueOf(response));
loading.dismiss();}
#Override
public void onFailure(Call<Routes> call, Throwable throwable) {
loading.dismiss();
Log.d(TAG, "onFailure" + throwable);
}
});
this is a log:
Response{protocol=http/1.1, code=403, message=Forbidden,
url=https://rasp.rw.by/api/ru/index/route/?from=Minsk&to=Warsaw}
if I take third-party sites where there are no headers, I get a response of 200 without problems. What am I doing wrong in this case? Thank you.
Oh, man, what are you doing. You can use annotations like #Query, #Header, etc.
public interface myAPIinterface {
#GET("/api/ru/index/route")
Call<Routes> getProducts(#Header("X-AppId:") String YOUR_APP_ID,
#Query("from") String from,
#Query("to") String to)
}
Then you can create request like this:
Retrofit retrofit = new Retrofit.Builder().
.baseUrl("https://rasp.rw.by")
.addConverterFactory(SimpleXmlConverterFactory.create())
.build();
retrofit.create(myAPIinterface.class).getProducts(myId, "Minsk", "Warsaw").enqueue ...
How It can help? You forgot to add header at second retrofit and then you have 403 error. So, You must add annotations, and this will be the last mistake when you forgot to put value to header/query/etc.
I'm trying to POST raw data using Retrofit.
I found many solution to POST JSON in Body using volley but the data I'm sending is not JSON.
my data is : {project_purpose: [EXECUTION]}
while hitting from the postman, I'm getting the data but not in android.
Please suggest me how to do this.
I'm trying to send as string but getting 500 in error code
I've also send the data in JsonObject, but not working..
Here is my code to call..
String bodyST = "{project_purpose: [purpose]}";
OR
JsonObject data = new JsonObject();
JSONArray jarray = new JSONArray();
jarray.put("EXECUTION");
data.addProperty("project_purpose", String.valueOf(jarray));
Call<JsonArray> call = apiInterface.getData(mAuthToken, "application/json", bodyST);
try this
I was facing the same problem when trying to POST data in raw form only and for this, i have wasted my whole day after that I got my solutions.
Your API interface should be like this:-
#POST(Constants.CONTACTS_URL)
Call<Object> getUser(#Body Map<String, String> body);
In your class where you are calling this
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiInterface apiInterface = retrofit.create(ApiInterface.class);
try {
Map<String, String> requestBody = new HashMap<>();
requestBody.put("email", "davinder.codeapex#gmail.com");
requestBody.put("password", "12345678");
Call<Object> call=apiInterface.getUser(requestBody);
call.enqueue(new Callback<Object>() {
#Override
public void onResponse(Call<Object> call, Response<Object> response) {
try {
JSONObject object=new JSONObject(new Gson().toJson(response.body()));
Log.e("TAG", "onResponse: "+object );
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<Object> call, Throwable t) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
Output
logcat:
Postman
Note:-i am not using any model class to get data after, retrieving data you can use anyway to store data.
Just send your body as string
#PUT("your-endpoint")
fun yourRequsetFunction(#Body body : String) :Response<YourResponseType>
I am building an Android APP where I use the Internet Game Database API through Mashape market place. I am using Retrofit for the get requests and getting data from the API requires an API key.
I got it to work but the API only return game ids and I want the game names and other information, but I am not sure how to add the fields. This is how Mashape query it:
HttpResponse<String> response = Unirest.get("https://igdbcom-internet-game-database-v1.p.mashape.com/games/?fields=name%2Crelease_dates")
.header("X-Mashape-Key", "API KEY HERE")
.header("Accept", "application/json")
.asString();
and this is my Retrofit Interface
public interface GamesAPIService {
#GET("/games/")
Call<List<GamesResponse>> gameList(#Query("mashape-key") String apikey);
}
I tried to use this
#GET("/games/?fields=name,release_dates")
But no luck, I also tried with #Field but didn't work either. Any ideas? Thanks.
Edit: Just to clarify when I add the "?fields=name,release_dates" I get 401 Unauthorized Error.
Firstly I think you need to add mashape key to all your request.
OkHttpClient httpClient = new OkHttpClient();
httpClient.addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request().newBuilder()
.addHeader("X-Mashape-Key", "API_KEY_HERE")
.addHeader("Accept", "application/json")
.build();
return chain.proceed(request);
}
});
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://igdbcom-internet-game-database-v1.p.mashape.com")
.client(httpClient)
.build();
And then this is information query.
public interface GamesAPIService {
#GET("/games")
Call<List<GamesResponse>> gameList(#Query("fields") String value);
}
And last thing for calling.
GamesAPIService gamesAPIService = retrofit.create(GamesAPIService.class);
Call<List<GamesResponse>> call = gamesAPIService.gameList("name,release_dates");
if (call!=null){
call.enqueue(new Callback<List<GamesResponse>>() {
#Override
public void onResponse(Call<List<GamesResponse>> call, Response<List<GamesResponse>> response) {
// handle success
}
#Override
public void onFailure(Throwable t) {
// handle failure
}
});
}