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
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 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.
I am new to retrofit and I am trying to send a comment to a specific media using retrofit and the Instagram API.
The Instagram API tells me that my request must be:
curl -F 'access_token=ACCESS-TOKEN'
-F 'text=This+is+my+comment'
https://api.instagram.com/v1/media/{media-id}/comments
and the JSON response is :
{
"meta":
{
"code": 200
},
"data": null
}
So I made this retrofit grammar:
#FormUrlEncoded
#POST("v1/media/{media_id}/comments")
Call<Object> postComment(
#Path("media_id") String mediaId,
#Field("access_token") String accessToken,
#Field("text") String text);
My Retrofit Service:
public class RestClient
{
public static RetrofitInstagram getRetrofitService()
{
return new Retrofit.Builder()
.baseUrl(Constants.AUTH_URL)
.addConverterFactory(GsonConverterFactory.create())
.build().create(RetrofitInstagram.class);
}
}
My call (inside an AlertDialog get the text from an EditText) is :
Call<Object> call = RestClient.getRetrofitService().postComment(data.get(idx).getId(), access_token, titleEditText.getText().toString());
call.enqueue(new Callback<Object>()
{
#Override
public void onResponse(Call<Object> call, Response<Object> response)
{
Log.d("response comment", ""+response.raw());
Toast.makeText(activity_instagram_feed_search.this, "Comments sent", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<Object> call, Throwable t)
{
Toast.makeText(activity_instagram_feed_search.this, "error", Toast.LENGTH_SHORT).show();
}
});
My problem here is that I am receiving a code 400 error (Missing client_id or access_token URL parameter.).
It's like the api think I am doing a GET request.
I am really confuse, I would appreciate some wisdom :).
I managed to find the solution to my question.
So Ben P was wrong and the Curl -F is x-www-form-urlencoded.
I am in sandbox account mode and forgot to add comments scope to my loggin
WebView request.
So my WebView url is now:
private final String url = Constants.AUTH_URL
+ "oauth/authorize/?client_id="
+ Constants.CLIENT_ID
+ "&redirect_uri="
+ Constants.REDIRECT_URI
+ "&response_type=token"
+ "&display=touch&scope=public_content+comments";
I'm trying to get a json list from a web service.
This is the json string return by server :
[{"categoryName":"Política"},{"categoryName":"Economía"},{"categoryName":"Cultura"},{"categoryName":"Deportes"}
The problem is converting in to the POJO. The special characters (í) it's appear like "Pol�tica".
This is the retrofit call function :
#GET("categories")
public Call<List<CategoryPojo>> getCategorias(#Query("sitename") String site)
this is the callback function:
Call<List<CategoryPojo>> call = restservice.getApiService().getCategorias(medio);
try {
call.enqueue(new Callback<List<CategoryPojo>>() {
#Override
public void onResponse(Call<List<CategoryPojo>> call, Response<List<CategoryPojo>> response) {
List<CategoryPojo> categories = response.body();
if (listener != null)
listener.onDataLoaded(categories);
}
#Override
public void onFailure(Call<List<CategoryPojo>> call, Throwable throwable) {
Log.e("Retrofit Error", throwable.getMessage());
}
});
this is the POJO:
public class CategoryPojo implements Serializable{
public CategoryPojo() { }
#SerializedName("categoryName")
private String name;
public String getName()
{
return this.name;
}
}
The result of the request to the Web services, (output in browser) is :
[{"categoryName":"Política"},{"categoryName":"Economía"},{"categoryName":"Cultura"},{"categoryName":"Deportes"},{"categoryName":"Salud"},{"categoryName":"Ciencia y Tecnología"},{"categoryName":"Medio Ambiente"},{"categoryName":"Medios"},{"categoryName":"Militar e Inteligencia"},{"categoryName":"Sociedad"}]
So, the return json has a good encoding...i think that maybe is about the way retrofit read the response.
I'm using retrofit-2.0.2, gson-2.6.1, converter-gson-2.0.2, okhttp-3.2.0.
Any help? please
You should check Content-type in the response headers. Look for the charset value and try to change that on the backend side to application/josn;charset=UTF-8. That worked for me.
I have a simple server rest endpoint running Spring -
#RestController
#RequestMapping("/services")
#Transactional
public class CustomerSignInService {
#Autowired
private CustomerDAO customerDao;
#RequestMapping("/customer/signin")
public Customer customerSignIn(#RequestParam(value = "customer") Customer customer) {
//Some Code Here...
return customer;
}
}
I'm trying to pass a Customer object from my Xamarin Android App using this method -
public JsonValue send(String url, SmartJsonSerializer obj)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
request.ContentType = "application/json";
request.Method = "POST";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(obj.toJsonString());
}
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
return JsonObject.Load(stream);
}
}
}
But i keep getting Bad Request Exception (Http Error 400) and obviously my code at the server side is not triggered.
SmartJsonSerializer uses JSON.NET to serialize the Customer object to string -
using System;
using Newtonsoft.Json;
namespace Shared
{
public class SmartJsonSerializer
{
public string toJson()
{
return JsonConvert.SerializeObject(this);
}
}
}
Any help appreciated,
thnx!
Typically if you are posting a complex object to an api like this, you would write it in the request body. You do appear to be doing this on the android side.
I am not familiar with Spring, but it looks that you are expecting customer as a url parameter - Try replacing #RequestParam with #RequestBody.
I was struggling with it for a while, but apparently the solution may be find in the server side.
If it helps, You can look at this
#RestController
#RequestMapping("/services")
#Transactional
public class SomeService {
#RequestMapping(value = "/user/signin", method = RequestMethod.POST)
#ResponseBody
public AppUser signIn(#RequestBody AppUser appUser) {
appUser.invoke();
return appUser;
}
}