I want to fetch live data from coinbase api. I'm using Retrofit to make API call I got a null response when i tried returning displaying the data
the json response from the api
JSON
{"data":{"base":"BTC","currency":"USD","amount":"9510.915"}}
The retrofit class for the returned data
RETROFIT
myC2C = RetrofitClient.getInstance("https://api.coinbase.com/v2/prices/").create(IMyC2C.class);
Call<DataList> call = myC2C.getPrice("USD");
call.enqueue(new Callback<DataList>() {
#Override
public void onResponse(Call<DataList> call, Response<DataList> response) {
if (!response.isSuccessful()){
usd_price.setText("Code: " + response.code());
return;
}
Log.d("resedatasync", new Gson().toJson(response.body().getDatas()));
}
#Override
public void onFailure(Call<DataList> call, Throwable t) {
usd_price.setText(t.getMessage());
}
The endpoint that calls get methods and parse the type of currency
ENDPOINT
#GET("spot")
Call<DataList> getPrice(#Query("currency") String currency);
the java model class here
**JAVA CLASS
import java.util.List;
public class DataList {
private Datas Datas;
public Datas getDatas() {
return Datas;
}
public void setDatas(Datas datas) {
this.Datas = datas;
}
}
package com.example.c2c.Model;
public class Datas {
private String base;
private String currency;
private float amount;
public String getBase() {
return base;
}
public void setBase(String base) {
this.base = base;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public float getAmount() {
return amount;
}
public void setAmount(float amount) {
this.amount = amount;
}
}
**
Related
I'm trying to get a JSON file using an URL, but the application is crashing.
JSON file api
MainActivity.java
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ApiService.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService service = retrofit.create(ApiService.class);
// Logs show error is in the code below
service.getPopulationData(new Callback<Flag> (){
#Override
public void onResponse(Call<Flag> call, Response<Flag> response) {
Log.d("JSONData", response.body().toString());
}
#Override
public void onFailure(Call<Flag> call, Throwable t) {
Log.d("JSONData", t.getMessage());
}
});
ApiService.java
public interface ApiService {
String BASE_URL = "http://www.androidbegin.com/";
#GET("tutorial/jsonparsetutorial.txt")
public void getPopulationData(Callback<Flag> callback) ;
}
Flag.java
public class Flag {
private int rank;
private String country;
private String population;
private String flag;
public int getRank() {
return rank;
}
public void setRank(int rank) {
this.rank = rank;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getPopulation() {
return population;
}
public void setPopulation(String population) {
this.population = population;
}
public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}
}
Edit: Error log can be found here: log
I've tried other solutions mentioned on stackoverflow, but I've been unable to get it right.
Also, I only want the flag URLs from the JSON file. How am I supposed to get it?
You will need the following two pojo class
JsonResponse.java
public class JsonResponse {
#SerializedName("worldpopulation")
#Expose
private List<Worldpopulation> worldpopulation = null;
public List<Worldpopulation> getWorldpopulation() {
return worldpopulation;
}
public void setWorldpopulation(List<Worldpopulation> worldpopulation) {
this.worldpopulation = worldpopulation;
}
}
Worldpopulation.java
public class Worldpopulation {
#SerializedName("rank")
#Expose
private Integer rank;
#SerializedName("country")
#Expose
private String country;
#SerializedName("population")
#Expose
private String population;
#SerializedName("flag")
#Expose
private String flag;
public Integer getRank() {
return rank;
}
public void setRank(Integer rank) {
this.rank = rank;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getPopulation() {
return population;
}
public void setPopulation(String population) {
this.population = population;
}
public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}
}
and make a retrofit call like below
service.getPopulationData(new Callback<JsonResponse> (){
#Override
public void onResponse(Call<JsonResponse> call, Response<JsonResponse> response) {
Log.d("JSONData", response.body().toString());
ArrayList<Worldpopulation> population=new ArrayList(response.body().getWorldpopulation());
}
#Override
public void onFailure(Call<JsonResponse> call, Throwable t) {
Log.d("JSONData", t.getMessage());
}
});
**** edited as per requirement ****
and change ApiService.java
public interface ApiService {
String BASE_URL = "http://www.androidbegin.com/";
#GET("tutorial/jsonparsetutorial.txt")
Call<JsonResponse> getPopulationData() ;
}
and call it like this
made an edit here
ApiService service = retrofit.create(ApiService.class);
Call<JsonResponse> call = service.getPopulationData();
call.enqueue(new Callback<JsonResponse> (){
#Override
public void onResponse(Call<JsonResponse> call, Response<JsonResponse> response) {
Log.d("JSONData", response.body().toString());
ArrayList<Worldpopulation> population=new ArrayList(response.body().getWorldpopulation());
}
#Override
public void onFailure(Call<JsonResponse> call, Throwable t) {
Log.d("JSONData", t.getMessage());
}
});
The json you are trying to parse with Retrofit contains a JSON Array as its root worldpopulation , So First you need a class WorldPopulation as follow:
public class WorldPopulation
{
private List<Flag> worldpopulation;
public List<Flag> getWorldpopulation() {
return worldpopulation;
}
public void setWorldpopulation(List<Flag> worldpopulation) {
this.worldpopulation = worldpopulation;
}
}
public interface ApiService {
String BASE_URL = "http://www.androidbegin.com/";
#GET("tutorial/jsonparsetutorial.txt")
public void getPopulationData(Callback<WorldPopulation> callback) ;
}
I use Retrofit 2.4 and try to get data from Asp.Net Core 2.0 WebApi Service.
Here Java class:
public class Category {
private int CategoryID;
private String Name;
private String Image;
public Category(){
Name="";
Image="";
}
public Category(int categoryID, String name, String image) {
Name = name;
Image = image;
CategoryID=categoryID;
}
public int getCategoryID() {return CategoryID;}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getImage() {
return Image;
}
public void setImage(String image) {
Image = image;
}
}
Here Retrofit code:
public class Common {
public static User CURRENT_USER;
public static String SERVER_NAME="http://ip_address:5000";
public static IApiService ApiService;
public Common()
{
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(SERVER_NAME)
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService = retrofit.create(IApiService.class);
}
}
public interface IApiService
{
#GET("api/Categories")
Call<List<Category>> GetCategoryColl();
}
And then i write server side via Asp.Net Core 2.0 WebApi.
I have a controller:
[Produces("application/json")]
[Route("api/Categories")]
public class CategoriesController : Controller
{
private readonly MovieAppServerContext _context;
public CategoriesController(MovieAppServerContext context)
{
_context = context;
}
// GET: api/Categories
[HttpGet]
public IEnumerable<Category> GetCategory()
{
return _context.Category;
}
// GET: api/Categories/5
[HttpGet("{id}")]
public async Task<IActionResult> GetCategory([FromRoute] int id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var category = await _context.Category.SingleOrDefaultAsync(m => m.CategoryID == id);
if (category == null)
{
return NotFound();
}
return Ok(category);
}
// PUT: api/Categories/5
[HttpPut("{id}")]
public async Task<IActionResult> PutCategory([FromRoute] int id, [FromBody] Category category)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != category.CategoryID)
{
return BadRequest();
}
_context.Entry(category).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!CategoryExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
// POST: api/Categories
[HttpPost]
public async Task<IActionResult> PostCategory([FromBody] Category category)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.Category.Add(category);
//await _context.SaveChangesAsync();
_context.SaveChanges();
return Ok(category);
}
// DELETE: api/Categories/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteCategory([FromRoute] int id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var category = await _context.Category.SingleOrDefaultAsync(m => m.CategoryID == id);
if (category == null)
{
return NotFound();
}
_context.Category.Remove(category);
// await _context.SaveChangesAsync();
_context.SaveChanges();
return Ok("Removed!");
}
private bool CategoryExists(int id)
{
return _context.Category.Any(e => e.CategoryID == id);
}
}
Here server side class of Category:
public class Category
{
[Key]
public int CategoryID { get; set; }
public String Name { get; set; }
public String Image { get; set; }
public Category()
{
}
public Category(String name, String image)
{
Name = name;
Image = image;
}
}
So, i check server code via Swagger and it works well: i get all data from Categories List.
But, when i try to get data from Android code via Retrofit - i get collection with empty objects : all fields are null or empty (i think it is default values).
So, here the code:
public class Home extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
List<Category> _categoryList =new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
//some code
Common.ApiService.GetCategoryColl().enqueue(new Callback<List<Category>>() {
#Override
public void onResponse(Call<List<Category>> call, Response<List<Category>> response) {
Log.i("GetCategories",response.message());
_categoryList=response.body();
// !!!! HERE. _category list contains objects but all of them
// are empty!
}
#Override
public void onFailure(Call<List<Category>> call, Throwable t) {
Log.e("GetCategories",t.getMessage());
}
});
}
}
So, i do not know, why it happens? How to fix that?
Thank you!
You haven't added #SerializedName("json-key-name") to your fields in the Java Category class:
#SerializedName("categoryId")
private int CategoryID;
#SerializedName("name")
private String Name;
#SerializedName("image")
private String Image;
Now GSON can map JSON response to the POJO properly.
By default Gson expects the field names to be the same as the Json ones, if you want to change this behavior, you have two options:
1.Use a FieldNamingPolicy, for your case it would be UPPER_CAMEL_CASE, below a sample how to do it for Retrofit:
Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(SERVER_NAME)
.addConverterFactory(GsonConverterFactory.create())
.build();
2. Use the SerializedName annotation on your java fields.
Until this api i had this ones and my code worked now i can not figure out what i need to get and what to put in Map also i don't know where to start to get this response into my app.
This api i know how work and i have working code for it :
https://gyazo.com/f2eb4858c48c31c5c48765a9e7512179
But this one api is really hard to figure for me.
https://gyazo.com/d2bad9dbe66bf7c51b169b54a68a003a
I really don't know what i need to put here in Map and how to get "result" array(if that is array list?? )
Thank you guys this is my unworking example.
Datas.class
package Model.BittrexApiModel;
public class Datas {
private Result result;
public Result getResult() {
return result;
}
public void setResult(Result result) {
this.result = result;
}
public Datas withDatas(Result result){
this.result=result;
return this;
}
}
Here is my Result POJO CLASS
package Model.BittrexApiModel;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Result {
#SerializedName("MarketName")
#Expose
private String marketName;
#SerializedName("High")
#Expose
private Double high;
#SerializedName("Low")
#Expose
private Double low;
#SerializedName("Volume")
#Expose
private Double volume;
#SerializedName("Last")
#Expose
private Double last;
#SerializedName("BaseVolume")
#Expose
private Double baseVolume;
#SerializedName("TimeStamp")
#Expose
private String timeStamp;
#SerializedName("Bid")
#Expose
private Double bid;
#SerializedName("Ask")
#Expose
private Double ask;
#SerializedName("OpenBuyOrders")
#Expose
private Integer openBuyOrders;
#SerializedName("OpenSellOrders")
#Expose
private Integer openSellOrders;
#SerializedName("PrevDay")
#Expose
private Double prevDay;
#SerializedName("Created")
#Expose
private String created;
public String getMarketName() {
return marketName;
}
public void setMarketName(String marketName) {
this.marketName = marketName;
}
public Result withMarketName(String marketName) {
this.marketName = marketName;
return this;
}
public Double getHigh() {
return high;
}
public void setHigh(Double high) {
this.high = high;
}
public Result withHigh(Double high) {
this.high = high;
return this;
}
public Double getLow() {
return low;
}
public void setLow(Double low) {
this.low = low;
}
public Result withLow(Double low) {
this.low = low;
return this;
}
public Double getVolume() {
return volume;
}
public void setVolume(Double volume) {
this.volume = volume;
}
public Result withVolume(Double volume) {
this.volume = volume;
return this;
}
public Double getLast() {
return last;
}
public void setLast(Double last) {
this.last = last;
}
public Result withLast(Double last) {
this.last = last;
return this;
}
public Double getBaseVolume() {
return baseVolume;
}
public void setBaseVolume(Double baseVolume) {
this.baseVolume = baseVolume;
}
public Result withBaseVolume(Double baseVolume) {
this.baseVolume = baseVolume;
return this;
}
public String getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
}
public Result withTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
return this;
}
public Double getBid() {
return bid;
}
public void setBid(Double bid) {
this.bid = bid;
}
public Result withBid(Double bid) {
this.bid = bid;
return this;
}
public Double getAsk() {
return ask;
}
public void setAsk(Double ask) {
this.ask = ask;
}
public Result withAsk(Double ask) {
this.ask = ask;
return this;
}
public Integer getOpenBuyOrders() {
return openBuyOrders;
}
public void setOpenBuyOrders(Integer openBuyOrders) {
this.openBuyOrders = openBuyOrders;
}
public Result withOpenBuyOrders(Integer openBuyOrders) {
this.openBuyOrders = openBuyOrders;
return this;
}
public Integer getOpenSellOrders() {
return openSellOrders;
}
public void setOpenSellOrders(Integer openSellOrders) {
this.openSellOrders = openSellOrders;
}
public Result withOpenSellOrders(Integer openSellOrders) {
this.openSellOrders = openSellOrders;
return this;
}
public Double getPrevDay() {
return prevDay;
}
public void setPrevDay(Double prevDay) {
this.prevDay = prevDay;
}
public Result withPrevDay(Double prevDay) {
this.prevDay = prevDay;
return this;
}
public String getCreated() {
return created;
}
public void setCreated(String created) {
this.created = created;
}
public Result withCreated(String created) {
this.created = created;
return this;
}
}
And here is my BittrexResponse.class ( i think this one is not working.)
package Model.BittrexApiModel;
import java.util.Map;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class BittrexResponse {
#SerializedName("success")
#Expose
private Boolean success;
#SerializedName("message")
#Expose
private String message;
#SerializedName("result")
#Expose
private Map<String, Result> datas;
public Map<String,Result> getDatas(){
return datas;
}
public void setDatas(Map<String,Result> datas){
this.datas=datas;
}
//private List<Result> result = new ArrayList<>();
//This is first original JSONSCHEMA2POJO - SAVING RESPONSE DON't WORK
// private List<Result> result = new ArrayList<Result>();
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public BittrexResponse withSuccess(Boolean success) {
this.success = success;
return this;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public BittrexResponse withMessage(String message) {
this.message = message;
return this;
}
ApiClient.class (working , tested on earlier examples)
package Model.CoinMarketCapApiModel;
import com.test.retrofit.CryptoCyber.Settings;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class ApiClient {
public static final String BASE_URL = Settings.getBase_url();
private static Retrofit retrofit = null;
public static Retrofit getClient() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
retrofit = new Retrofit.Builder()
.client(client)
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit;
}
}
I hope someone will help me to figure out why i don't know get data and save it to map...
P.s. here is link for api
CLICK HERE
Here's a possible way to design your classes to correctly parse the response.
ApiResponse
public class ApiResponse {
private boolean success;
private String message;
#SerializedName("result")
private List<Market> markets;
// Other fields + getters&setters
...
}
Market
public class Market {
#SerializedName("MarketName")
private String marketName;
#SerializedName("High")
private double high;
#SerializedName("Low")
private double low;
#SerializedName("Volume")
private double volume;
// Other fields + getters&setters
...
}
Main
public class Main {
public static void main(String[] args) throws IOException {
Retrofit retrofit = createRetrofit();
Api api = retrofit.create(Api.class);
retrofit2.Response<ApiResponse> response = api.getMarketSummaries().execute();
if (!response.isSuccessful()) {
// Handle error case
} else {
ApiResponse marketApiResponse = response.body();
System.out.println(marketApiResponse);
}
}
private static Retrofit createRetrofit() {
return new Retrofit.Builder()
.baseUrl("https://bittrex.com/api/v1.1/public/")
.addConverterFactory(GsonConverterFactory.create())
.build();
}
}
It will print something like this (only first item of the list is reported for the sake of brevity):
ApiResponse{success=true, message='', markets=[Market{marketName='BTC-2GIVE', high=1.1E-6, low=9.7E-7, volume=3499023.70109898},
I'm new to Retrofit and JSON and I don't really know how to parse the next json string:
{
"weight":[
{ "bmi":21,
"date":"2016-12-09",
"fat":14.059000015258789,
"logId":1222222222222,
"source":"Aria",
"time":"11:58:24",
"weight":68
},
{ "bmi":21.83,
"date":"2016-12-14",
"logId":1222222222223,
"source":"Aria",
"time":"14:31:39",
"weight":70.7
}
]
}
I just want "weight" and "date" inside weight array. I've created a pojo class following some examples but it's not working.
Also when trying it with my pojo class I couldn't get "weight" as a string (I'll then use it as a double) using .string().
(I know using .toString() shows something like "com.myPackage.MyPojo#xxxx").
For now, I have only been able to get the whole json through ResponseBody:
Call<ResponseBody>call = repository.getFitbitApi().getData();
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
try {
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
What am I doing wrong? Here are my pojo classes, just an attempt...:
public class WeightList {
#SerializedName("weight")
#Expose
private ArrayList<WeightLogFitbit> weight = new ArrayList<>();
public WeightList(){
}
public ArrayList<WeightLogFitbit> getWeight() {
return weight;
}
public void setWeight(ArrayList<WeightLogFitbit> weight) {
this.weight = weight;
}
}
And:
public class WeightLogFitbit {
//Variables in my JSON
#SerializedName("bmi")
#Expose
private String bmi;
#SerializedName("date")
#Expose
private String date;
#SerializedName("logId")
#Expose
private String logId;
#SerializedName("source")
#Expose
private String source;
#SerializedName("time")
#Expose
private String time;
#SerializedName("weight")
#Expose
private double weight;
#SerializedName("fat")
#Expose
private String fat;
public WeightLogFitbit(){}
//Getters and setters
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getBmi(){
return bmi;
}
public void setBmi(String bmi) {
this.bmi = bmi;
}
//
public String getFat(){
return fat;
}
public void setFat(String fat) {
this.fat = fat;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getLogId() {
return logId;
}
public void setLogId(String logId) {
this.logId = logId;
}
}
NOTE: I'm using RxSocialConnect library, which implements RxJava, Retrofit 2, OkHttp3 and gson, just in case. I did this following this example.
Rest of classes I'm using:
public class FitbitBtnActivity extends AppCompatActivity {
private FitbitRepository repository;
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fitbit_btn);
repository = new FitbitRepository();
setUpFitbit();
}
private void setUpFitbit() {
findViewById(R.id.fitbitbtn).setOnClickListener(v ->
RxSocialConnect.with(this, repository.fitbitService())
.subscribe(response -> response.targetUI().showToken(response.token()),
error -> showError(error))
);
findViewById(R.id.retrievebtn).setOnClickListener(v -> {
Call<ResponseBody>call = repository.getFitbitApi().getData();
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
try {
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
//Original code from example in RxSocialConnect
/*.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<Object>() {
#Override
public void call(Object user) {
FitbitBtnActivity.this.showUserProfile(user.toString());
}
},
error -> FitbitBtnActivity.this.showError(error));*/
}
);
}
And:
public class FitbitRepository {
private final FitbitApiRest fitbitApi;
public FitbitRepository() {
fitbitApi = initFitbitApiRest();
}
private FitbitApiRest initFitbitApiRest() {
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new OAuth2Interceptor(FitbitApi20.class))
.build();
return new Retrofit.Builder()
.baseUrl(FitbitApiRest.URL_BASE)
.client(client)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build().create(FitbitApiRest.class);
}
FitbitApiRest getFitbitApi() {
return fitbitApi;
}
interface FitbitApiRest {
String URL_BASE = "https://api.fitbit.com";
#GET("myrequest.json")
Call<ResponseBody> getData();
}
OAuth20Service fitbitService() {
final String client_id = "xxxxx";
final String client_secret = "1xxxxxxxxxxxxxxxxxx";
final String redirect_uri = "http://example.com";
final String permissions = "weight";
return new ServiceBuilder()
.apiKey(client_id)
.apiSecret(client_secret)
.callback(redirect_uri)
.scope(permissions)
.build(FitbitApi20.instance());
}
}
You need to add this to your dependencies:
compile 'com.squareup.retrofit2:converter-gson:your-version'
and then add a gson converter to your Retrofit instance like this:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.example.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
and change your call in the api to return WeightList:
Call<WeightList> getData();
I have an application (Spring 4 MVC+Hibernate 4+MySQL+Maven integration example using annotations) , integrating Spring with Hibernate using annotation based configuration.
Here my controller:
#Controller
public class RestController {
#RequestMapping(value = { "/restCallBack" }, method = RequestMethod.GET)
#ResponseBody
public String performCallBack(#RequestBody RestCallBack restCallBack) {
Preconditions.checkNotNull( restCallBack );
return "computerList";
}
but when I put this on the browser I get a 400:
http://localhost:8080/myApp/restCallBack?devideId=devideId&time=time&duplicate=duplicate&snr=snr&station=station&data=data&avgSignal=avgSignal&lat=lat&lng=lng&rssi=rssi&seqNumber=seqNumber
Here the RestCallBack class
public class RestCallCallBack {
private String devideId;
private String time;
private String duplicate;
private String snr;
private String station;
private String data;
private String avgSignal;
private String lat;
private String lng;
private String rssi;
private String seqNumber;
public String getDevideId() {
return devideId;
}
public void setDevideId(String devideId) {
this.devideId = devideId;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getDuplicate() {
return duplicate;
}
public void setDuplicate(String duplicate) {
this.duplicate = duplicate;
}
public String getSnr() {
return snr;
}
public void setSnr(String snr) {
this.snr = snr;
}
public String getStation() {
return station;
}
public void setStation(String station) {
this.station = station;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public String getAvgSignal() {
return avgSignal;
}
public void setAvgSignal(String avgSignal) {
this.avgSignal = avgSignal;
}
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
public String getLng() {
return lng;
}
public void setLng(String lng) {
this.lng = lng;
}
public String getRssi() {
return rssi;
}
public void setRssi(String rssi) {
this.rssi = rssi;
}
public String getSeqNumber() {
return seqNumber;
}
public void setSeqNumber(String seqNumber) {
this.seqNumber = seqNumber;
}
}
Based on the example request query string, it seems like you are attempting to pass request parameters to the server rather than a request body. If so, take a look at #RequestParam, e.g.
#Controller
public class RestController {
#RequestMapping(value = { "/restCallBack" }, method = RequestMethod.GET)
#ResponseBody
public String performCallBack(#RequestParam("devideId") String devideId,
#RequestParam("time") String time,
#RequestParam("duplicate") String duplicate,
/* more request params... */ {
RestCallCallBack restCallCallBack = new RestCallCallBack();
restCallCallBack.setDevideId(devideId);
restCallCallBack.setTime(time);
restCallCallBack.setDuplicate(duplicate);
// set more params...
// perform validation
return "computerList";
}
}
You can also specify which params are optional by by setting the #RequestParam's required attribute to false.
More information available in the Binding request parameters to method parameters with #RequestParam paragraph in the Spring Reference docs.