Im trying to post data with retrofit with jwt bearer authentication, but when i debug response code, its
error 400, and the message is body = null
This is my Intefrace class
#Headers({"accept: text/plain","Content-Type: application/json-patch+json" })
#POST("services/app/ProjectService/Create")
Call<ProjectRequest> postProject(#Header("Authorization") String token,
#Body ProjectRequest projectRequest
);
This is my model class
public class ProjectRequest {
#SerializedName("name")
#Expose
private String name;
#SerializedName("description")
#Expose
private String description;
#SerializedName("ownerId")
#Expose
private int ownerId;
#SerializedName("startPeriod")
#Expose
private String startPeriod;
#SerializedName("endPeriod")
#Expose
private String endPeriod;
#SerializedName("isDraft")
#Expose
private boolean isDraft;
#SerializedName("ownerName")
#Expose
private String ownerName;
#SerializedName("pitId")
#Expose
private int pitId;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getOwnerId() {
return ownerId;
}
public void setOwnerId(int ownerId) {
this.ownerId = ownerId;
}
public String getStartPeriod() {
return startPeriod;
}
public void setStartPeriod(String startPeriod) {
this.startPeriod = startPeriod;
}
public String getEndPeriod() {
return endPeriod;
}
public void setEndPeriod(String endPeriod) {
this.endPeriod = endPeriod;
}
public boolean isDraft() {
return isDraft;
}
public void setDraft(boolean draft) {
isDraft = draft;
}
public String getOwnerName() {
return ownerName;
}
public void setOwnerName(String ownerName) {
this.ownerName = ownerName;
}
public int getPitId() {
return pitId;
}
public void setPitId(int pitId) {
this.pitId = pitId;
}
And the main class is
private void initApi() {
projectApi = ApiClient.getClient().create(ProjectApi.class);
}
private void postProject(final boolean isOnline) {
if (isOnline) {
final ProjectRequest projectRequest = new ProjectRequest();
projectRequest.setName(projectName);
projectRequest.setDescription(description);
projectRequest.setOwnerId(1);
projectRequest.setStartPeriod(dateStart);
projectRequest.setEndPeriod(dateEnd);
projectRequest.setDraft(true);
projectRequest.setOwnerName("yogi kun");
projectRequest.setPitId(1);
Call<ProjectRequest> callProject = projectApi.postProject(" Bearer eyJ0eXAiOiJKV1QiLCJub25jZSI6Il and so . . . ",
projectRequest);
callProject.enqueue(new Callback<ProjectRequest>() {
#Override
public void onResponse(#NotNull Call<ProjectRequest> call, #NotNull Response<ProjectRequest> response) {
if (response.isSuccessful()) {
try {
Toast.makeText(getContext(), "Success", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
String message = "";
if (e.getMessage() != null) {
message = e.getMessage();
}
Toast.makeText(getContext(), "Failed " + message, Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getContext(), "Failed " + response, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(#NotNull Call<ProjectRequest> call, #NotNull Throwable t) {
Toast.makeText(getContext(), "Failure" + t, Toast.LENGTH_SHORT).show();
}
});
}
And the error is
enter image description here
And
enter image description here
Might be an issue with how the JSON is formatted, compared to what you're expecting. Are you able to use something like Postman and try this API call to see the format it comes back? Can't tell that much but the error message shown is finding some array somewhere in the JSON
Related
I have face a problem retrofit library in android java.
here is the json Body
{
"title":"Android ",
"type":"project",
"category_id":"1",
"tags":["swift","java","android"],
"end_date":"2021-9-30",
"description":"testing",
"budget":"500"
}
This the pojo class
public class draftedJobPostModel {
private String title;
private String type;
private int category_id;
ArrayList<String> tags;
private String end_date;
private String description;
private int budget;
private String post_type;
public draftedJobPostModel() {
}
public draftedJobPostModel(String title, String type, int category_id, ArrayList<String> tags, String end_date, String description, int budget, String post_type) {
this.title = title;
this.type = type;
this.category_id = category_id;
this.tags = tags;
this.end_date = end_date;
this.description = description;
this.budget = budget;
this.post_type = post_type;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getCategory_id() {
return category_id;
}
public void setCategory_id(int category_id) {
this.category_id = category_id;
}
public ArrayList<String> getTags() {
return tags;
}
public void setTags(ArrayList<String> tags) {
this.tags = tags;
}
public String getEnd_date() {
return end_date;
}
public void setEnd_date(String end_date) {
this.end_date = end_date;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getBudget() {
return budget;
}
public void setBudget(int budget) {
this.budget = budget;
}
public String getPost_type() {
return post_type;
}
public void setPost_type(String post_type) {
this.post_type = post_type;
}
}
Add value from chip:
ArrayList<String> arrayTags = new ArrayList<>();
for (int i=0;i<chipGroup.getChildCount();i++)
{
Chip chip = (Chip) chipGroup.getChildAt(i);
arrayTags.add(chip.getText().toString());
}
retrofit call method:
Service service = Client.retrofit.create(Service.class);
Call<createJobPostModel> call = service.createJob("Bearer"+" "+token,title,jobtype,fieldId, arrayTags,date,budget,description);
call.enqueue(new Callback<createJobPostModel>() {
#Override
public void onResponse(Call<createJobPostModel> call, Response<createJobPostModel> response) {
if (response.isSuccessful()){
/* Toast.makeText(getActivity(), "Success", Toast.LENGTH_SHORT).show();*/
Toast.makeText(getActivity(),arrayTags.toString(), Toast.LENGTH_LONG).show();
/*arrayTags.clear();*/
}else{
Toast.makeText(getActivity(), "Error", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<createJobPostModel> call, Throwable t) {
Toast.makeText(getActivity(), "Failed", Toast.LENGTH_SHORT).show();
}
});
Everything is ok but when i pass the arraylist its shows only last index of array value in database.
here is the return value:
"tags": "Android",
but i want this:
"tags": [
"swift",
"IOS",
"android"
],
Am new to Retrofit and API Integration. Am trying to display response in a toast. Am using Retrofit for an API call. But the response from Retrofit is showing null . There is no response instead null. I don't Know may be am doing in a wrong way. Here is my code. Please Help me
Below is sample API
Params:
{
"DeviceID": "Hawqr-jagadish-test-device",
"DeviceType": "1",
"DeviceName": "Jagadish Device",
"AppVersion": 1
}
Response:
{
"success": true,
"extras": {
"Status": "Device Splash Screen Completed Successfully",
"Env_Type": 2,
"ApiKey": "4ae3a7e5-2622-4376-bc0d-a0ccd6c0405a",
"Whether_Latest_Version": true,
"SocketIO_Data": {
"socket_host": "https://xsocket.hawqr.com",
"socketjs_link": "https://xsocket.hawqr.com/socket.io/socket.io.js"
}
}
}
This My Main Activity. In main activity i have call API
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(MainActivity.this,LoginActivity.class);
startActivity(intent);
finish();
}
},SPLASH_SCREEN );
String DeviceID = "Hawqr-jagadish-test-device";
String DeviceType = "1";
String DeviceName = "Jagadish Device";
Integer AppVersion = 1 ;
SplashRequest splashRequest = new SplashRequest();
splashRequest.setDeviceID(DeviceID);
splashRequest.setDeviceType(DeviceType);
splashRequest.setDeviceName(DeviceName);
splashRequest.setAppVersion(AppVersion);
SplashScreen(splashRequest);
}
public void SplashScreen(SplashRequest splashRequest){
UserService userService = ApiClient.getRetrofit().create(UserService.class);
Call<SplashResponse> splashResponseCall = userService.splashScreen(splashRequest);
splashResponseCall.enqueue(new Callback<SplashResponse>() {
#Override
public void onResponse(Call<SplashResponse> call, Response<SplashResponse> response) {
Gson gson = new Gson();
String successResponse = gson.toJson(response.body());
Toast.makeText(MainActivity.this,successResponse,Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(Call<SplashResponse> call, Throwable t) {
String msg = t.getLocalizedMessage();
Toast.makeText(MainActivity.this,msg,Toast.LENGTH_SHORT).show();
}
});
}
}
These are my Model classes for Parameters
public class SplashRequest {
public String DeviceID;
public String DeviceType;
public String DeviceName;
public Integer AppVersion;
public String getDeviceID() {
return DeviceID;
}
public void setDeviceID(String deviceID) {
DeviceID = deviceID;
}
public String getDeviceType() {
return DeviceType;
}
public void setDeviceType(String deviceType) {
DeviceType = deviceType;
}
public String getDeviceName() {
return DeviceName;
}
public void setDeviceName(String deviceName) {
DeviceName = deviceName;
}
public Integer getAppVersion() {
return AppVersion;
}
public void setAppVersion(Integer appVersion) {
AppVersion = appVersion;
}
Another Model Class
public String ApiKey;
public String Env_Type;
public String Status;
public String Whether_Latest_Version;
public SplashResponse(String apiKey, String env_Type, String status, String whether_Latest_Version) {
ApiKey = apiKey;
Env_Type = env_Type;
Status = status;
Whether_Latest_Version = whether_Latest_Version;
}
public String getApiKey() {
return ApiKey;
}
public void setApiKey(String apiKey) {
ApiKey = apiKey;
}
public String getEnv_Type() {
return Env_Type;
}
public void setEnv_Type(String env_Type) {
Env_Type = env_Type;
}
public String getStatus() {
return Status;
}
public void setStatus(String status) {
Status = status;
}
public String getWhether_Latest_Version() {
return Whether_Latest_Version;
}
public void setWhether_Latest_Version(String whether_Latest_Version) {
Whether_Latest_Version = whether_Latest_Version;
}
}
This My Interface Class for Splash Response and Request
#POST("authenticate/")
Call<SplashResponse> splashScreen(#Body SplashRequest splashRequest);
The model class Splash Response was wrong, I made changes to it and its working fine.
public class SplashResponse implements Serializable {
#SerializedName("success")
#Expose
private Boolean success;
#SerializedName("extras")
#Expose
private Extras extras;
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public Extras getExtras() {
return extras;
}
public void setExtras(Extras extras) {
this.extras = extras;
}
public class Extras {
#SerializedName("Status")
#Expose
private String status;
#SerializedName("Env_Type")
#Expose
private Integer envType;
#SerializedName("ApiKey")
#Expose
private String apiKey;
#SerializedName("Whether_Latest_Version")
#Expose
private Boolean whetherLatestVersion;
#SerializedName("SocketIO_Data")
#Expose
private SocketIOData socketIOData;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Integer getEnvType() {
return envType;
}
public void setEnvType(Integer envType) {
this.envType = envType;
}
public String getApiKey() {
return apiKey;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
public Boolean getWhetherLatestVersion() {
return whetherLatestVersion;
}
public void setWhetherLatestVersion(Boolean whetherLatestVersion) {
this.whetherLatestVersion = whetherLatestVersion;
}
public SocketIOData getSocketIOData() {
return socketIOData;
}
public void setSocketIOData(SocketIOData socketIOData) {
this.socketIOData = socketIOData;
}
#SerializedName("code")
#Expose
private Integer code;
#SerializedName("msg")
#Expose
private String msg;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
public class SocketIOData {
#SerializedName("socket_host")
#Expose
private String socketHost;
#SerializedName("socketjs_link")
#Expose
private String socketjsLink;
public String getSocketHost() {
return socketHost;
}
public void setSocketHost(String socketHost) {
this.socketHost = socketHost;
}
public String getSocketjsLink() {
return socketjsLink;
}
public void setSocketjsLink(String socketjsLink) {
this.socketjsLink = socketjsLink;
}
}
}
Next In My Main Activity I made these changes
public void SplashScreen(SplashRequest splashRequest){
UserService userService = ApiClient.getRetrofit().create(UserService.class);
Call<SplashResponse> splashResponseCall = userService.splashScreen(splashRequest);
splashResponseCall.enqueue(new Callback<SplashResponse>() {
#Override
public void onResponse(Call<SplashResponse> call, Response<SplashResponse> response) {
Gson gson = new Gson();
String successResponse = gson.toJson(response.body());
SplashResponse response1 = response.body();
if (response.isSuccessful()) {
Toast.makeText(MainActivity.this, response1.getExtras().getStatus(), Toast.LENGTH_LONG).show();
}else {
//Toast.makeText(MainActivity.this, response1.getExtras().getStatus(), Toast.LENGTH_LONG).show();
if(response1.getExtras().getCode() == 1){
Toast.makeText(MainActivity.this, response1.getExtras().getMsg(), Toast.LENGTH_LONG).show();
}else{
Toast.makeText(MainActivity.this, response1.getExtras().getMsg(), Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onFailure(Call<SplashResponse> call, Throwable t) {
String msg = t.getLocalizedMessage();
Toast.makeText(MainActivity.this,msg,Toast.LENGTH_SHORT).show();
}
});
}
I am trying to making a POST request using retrofit2 but I am getting ErrorCode: 401. I am not finding the proper solution on the web that can help me out to solve my problem.
Data load for POST request
InsertAcitvity.java
private void insertData() {
String name = mName.getText().toString().trim();
String email = mEmail.getText().toString().trim();
String phone = mPhone.getText().toString().trim();
String full_address = mFull_address.getText().toString().trim();
String name_of_university = mName_of_university.getText().toString().trim();
int graduation_year = Integer.parseInt(mGraduation_year.getText().toString().trim());
double cgpa = Double.parseDouble(mCgpa.getText().toString().trim()) ;
String experience_in_months = mExperience_in_months.getText().toString().trim();
String current_work_place_name = mCurrent_work_place_name.getText().toString().trim();
String applying_in = mApplying_in.getText().toString().trim();
int expected_salary = Integer.parseInt(mExpected_salary.getText().toString().trim()) ;
String reference = mFeference.getText().toString().trim();
String github_project_url = mGithub_project_url.getText().toString().trim();
long creationTime= System.currentTimeMillis();
long updateTime= System.currentTimeMillis();
//String token = LoginActivity.token;
Intent intent = getIntent();
// declare token as member variable
String token = intent.getStringExtra("TOKEN_STRING");
String CvUniqueId = UUID.randomUUID().toString();
String tsync_id = UUID.randomUUID().toString();
cvFileObject = new CvFileObject(CvUniqueId);
mainObject = new MainObjectClass(tsync_id, name, email, phone, full_address, name_of_university, graduation_year, cgpa, experience_in_months,
current_work_place_name, applying_in, expected_salary,field_buzz_reference, github_project_url, cvFileObject, creationTime, updateTime);
ClientMethod clientMethod = ApiClient.getClient().create(ClientMethod.class);
Call<MainResponseObjectClass> call = clientMethod.getValue(token,mainObject);
call.enqueue(new Callback<MainResponseObjectClass>() {
#Override
public void onResponse(#NonNull Call<MainResponseObjectClass> call, #NonNull Response<MainResponseObjectClass> response) {
if (response.isSuccessful()){
Toast.makeText(InsertActivity.this, response.body().getTsync_id(), Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(InsertActivity.this, "access denied:(",Toast.LENGTH_LONG).show();
Log.d("ErrorCode", "onResponse: " + response.code());
}
}
#Override
public void onFailure(#NonNull Call<MainResponseObjectClass> call, #NonNull Throwable t) {
Log.d("Error", "onFailure: " + t.getMessage());
}
});
}
ClientMethod.java
public interface ClientMethod {
#POST("api/login/")
Call<Token>login(#Body Login login);
#POST("/api/v0/recruiting-entities/")
Call<MainResponseObjectClass> getValue(#Header("Authorization") String AutToken, #Body MainObjectClass mainObjectClass);
}
ApliClient.java
public class ApiClient {
public static final String BASE_URL = "https://myapi.test.com";
private static Retrofit retrofit = null;
public static Retrofit getClient(){
if (retrofit == null){
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
POST request code
CvFileObject.java
public class CvFileObject {
#SerializedName("tsync_id")
private String tsync_id;
public CvFileObject(String tsync_id) {
this.tsync_id = tsync_id;
}
public String getTsync_id() {
return tsync_id;
}
public void setTsync_id(String tsync_id) {
this.tsync_id = tsync_id;
}
}
MainObjectClass.java
public class MainObjectClass {
#SerializedName("tsync_id")
private String tsync_id;
#SerializedName("name")
private String name;
#SerializedName("email")
private String email;
#SerializedName("phone")
private String phone;
#SerializedName("full_address")
private String full_address;
#SerializedName("name_of_university")
private String name_of_university;
#SerializedName("graduation_year")
private int graduation_year;
#SerializedName("cgpa")
private double cgpa;
#SerializedName("experience_in_months")
private String experience_in_months;
#SerializedName("current_work_place_name")
private String current_work_place_name;
#SerializedName("applying_in")
private String applying_in;
#SerializedName("expected_salary")
private int expected_salary;
#SerializedName("reference")
private String reference;
#SerializedName("github_project_url")
private String github_project_url;
#SerializedName("cv_file")
private CvFileObject fileObject;
#SerializedName("on_spot_update_time")
long on_spot_update_time;
#SerializedName("on_spot_creation_time")
long on_spot_creation_time;
public MainObjectClass(String tsync_id, String name, String email, String phone, String full_address,
String name_of_university, int graduation_year, double cgpa, String experience_in_months,
String current_work_place_name, String applying_in, int expected_salary, String reference,
String github_project_url, CvFileObject fileObject, long on_spot_update_time, long on_spot_creation_time) {
this.tsync_id = tsync_id;
this.name = name;
this.email = email;
this.phone = phone;
this.full_address = full_address;
this.name_of_university = name_of_university;
this.graduation_year = graduation_year;
this.cgpa = cgpa;
this.experience_in_months = experience_in_months;
this.current_work_place_name = current_work_place_name;
this.applying_in = applying_in;
this.expected_salary = expected_salary;
this.reference = reference;
this.github_project_url = github_project_url;
this.fileObject = fileObject;
this.on_spot_update_time = on_spot_update_time;
this.on_spot_creation_time = on_spot_creation_time;
}
public String getTsync_id() {
return tsync_id;
}
public void setTsync_id(String tsync_id) {
this.tsync_id = tsync_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getFull_address() {
return full_address;
}
public void setFull_address(String full_address) {
this.full_address = full_address;
}
public String getName_of_university() {
return name_of_university;
}
public void setName_of_university(String name_of_university) {
this.name_of_university = name_of_university;
}
public int getGraduation_year() {
return graduation_year;
}
public void setGraduation_year(int graduation_year) {
this.graduation_year = graduation_year;
}
public double getCgpa() {
return cgpa;
}
public void setCgpa(double cgpa) {
this.cgpa = cgpa;
}
public String getExperience_in_months() {
return experience_in_months;
}
public void setExperience_in_months(String experience_in_months) {
this.experience_in_months = experience_in_months;
}
public String getCurrent_work_place_name() {
return current_work_place_name;
}
public void setCurrent_work_place_name(String current_work_place_name) {
this.current_work_place_name = current_work_place_name;
}
public String getApplying_in() {
return applying_in;
}
public void setApplying_in(String applying_in) {
this.applying_in = applying_in;
}
public int getExpected_salary() {
return expected_salary;
}
public void setExpected_salary(int expected_salary) {
this.expected_salary = expected_salary;
}
public String reference() {
return reference;
}
public void setreference(String reference) {
this.reference = reference;
}
public String getGithub_project_url() {
return github_project_url;
}
public void setGithub_project_url(String github_project_url) {
this.github_project_url = github_project_url;
}
public CvFileObject getFileObject() {
return fileObject;
}
public void setFileObject(CvFileObject fileObject) {
this.fileObject = fileObject;
}
public long getOn_spot_update_time() {
return on_spot_update_time;
}
public void setOn_spot_update_time(long on_spot_update_time) {
this.on_spot_update_time = on_spot_update_time;
}
public long getOn_spot_creation_time() {
return on_spot_creation_time;
}
public void setOn_spot_creation_time(long on_spot_creation_time) {
this.on_spot_creation_time = on_spot_creation_time;
}
}
POST request response code
CvFileResponseObject.java
public class CvFileResponseObject {
#SerializedName("id")
int id;
#SerializedName("tsync_id")
private String tsync_id;
public CvFileResponseObject(String tsync_id) {
this.tsync_id = tsync_id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTsync_id() {
return tsync_id;
}
public void setTsync_id(String tsync_id) {
this.tsync_id = tsync_id;
}
}
MainResponseObjectClass.java
public class MainResponseObjectClass {
#SerializedName("tsync_id")
private int tsync_id;
#SerializedName("name")
private String name;
#SerializedName("email")
private String email;
#SerializedName("phone")
private String phone;
#SerializedName("full_address")
private String full_address;
#SerializedName("name_of_university")
private String name_of_university;
#SerializedName("graduation_year")
private int graduation_year;
#SerializedName("cgpa")
private double cgpa;
#SerializedName("experience_in_months")
private String experience_in_months;
#SerializedName("current_work_place_name")
private String current_work_place_name;
#SerializedName("applying_in")
private String applying_in;
#SerializedName("expected_salary")
private String expected_salary;
#SerializedName("reference")
private String reference;
#SerializedName("github_project_url")
private String github_project_url;
#SerializedName("cv_file")
private CvFileResponseObject cvFileResponseObject;
#SerializedName("on_spot_update_time")
long on_spot_update_time;
#SerializedName("on_spot_creation_time")
long on_spot_creation_time;
#SerializedName("success")
private boolean success;
#SerializedName("message")
private String message;
public MainResponseObjectClass(int tsync_id, String name, String email, String phone,
String full_address, String name_of_university, int graduation_year,
double cgpa, String experience_in_months, String current_work_place_name,
String applying_in, String expected_salary, String reference,
String github_project_url, CvFileResponseObject cvFileResponseObject, long on_spot_update_time,
long on_spot_creation_time, boolean success, String message) {
this.tsync_id = tsync_id;
this.name = name;
this.email = email;
this.phone = phone;
this.full_address = full_address;
this.name_of_university = name_of_university;
this.graduation_year = graduation_year;
this.cgpa = cgpa;
this.experience_in_months = experience_in_months;
this.current_work_place_name = current_work_place_name;
this.applying_in = applying_in;
this.expected_salary = expected_salary;
this.reference = reference;
this.github_project_url = github_project_url;
this.cvFileResponseObject = cvFileResponseObject;
this.on_spot_update_time = on_spot_update_time;
this.on_spot_creation_time = on_spot_creation_time;
this.success = success;
this.message = message;
}
public int getTsync_id() {
return tsync_id;
}
public void setTsync_id(int tsync_id) {
this.tsync_id = tsync_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getFull_address() {
return full_address;
}
public void setFull_address(String full_address) {
this.full_address = full_address;
}
public String getName_of_university() {
return name_of_university;
}
public void setName_of_university(String name_of_university) {
this.name_of_university = name_of_university;
}
public int getGraduation_year() {
return graduation_year;
}
public void setGraduation_year(int graduation_year) {
this.graduation_year = graduation_year;
}
public double getCgpa() {
return cgpa;
}
public void setCgpa(double cgpa) {
this.cgpa = cgpa;
}
public String getExperience_in_months() {
return experience_in_months;
}
public void setExperience_in_months(String experience_in_months) {
this.experience_in_months = experience_in_months;
}
public String getCurrent_work_place_name() {
return current_work_place_name;
}
public void setCurrent_work_place_name(String current_work_place_name) {
this.current_work_place_name = current_work_place_name;
}
public String getApplying_in() {
return applying_in;
}
public void setApplying_in(String applying_in) {
this.applying_in = applying_in;
}
public String getExpected_salary() {
return expected_salary;
}
public void setExpected_salary(String expected_salary) {
this.expected_salary = expected_salary;
}
public String getField_buzz_reference() {
return field_buzz_reference;
}
public void setFeference(String reference) {
this.field_buzz_reference = reference;
}
public String getGithub_project_url() {
return github_project_url;
}
public void setGithub_project_url(String github_project_url) {
this.github_project_url = github_project_url;
}
public CvFileResponseObject getCvFileResponseObject() {
return cvFileResponseObject;
}
public void setCvFileResponseObject(CvFileResponseObject cvFileResponseObject) {
this.cvFileResponseObject = cvFileResponseObject;
}
public long getOn_spot_update_time() {
return on_spot_update_time;
}
public void setOn_spot_update_time(long on_spot_update_time) {
this.on_spot_update_time = on_spot_update_time;
}
public long getOn_spot_creation_time() {
return on_spot_creation_time;
}
public void setOn_spot_creation_time(long on_spot_creation_time) {
this.on_spot_creation_time = on_spot_creation_time;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
Here I can see two APIs. But I am not sure which to which API you are getting 401. I can help you with the possibilities that you could check and please feel free to ask.
Assuming you are getting 401 for login API - the reason could be you are trying with wrong credentials.
Assuming you are getting 401 for getValue API - the reason could be you might passing the wrong token which you got from login response. Especially you need to cross-check the header with key and values.
And I have one suggestion - you could use header in Interceptor with retrofit setup itself.
While working on retrofit, I used http://www.jsonschema2pojo.org this site to convert json to POJO. But I got an error while parsing JSON like this. Its saying Expected BEGIN_OBJECT but was BEGIN_ARRAY.
[
{
"uuid": "12e26270-b506-11e9-ad81-5f542bb63d66",
"first_name": "Nohar",
"last_name": "Kumar",
"title": "Premier League Player",
"gender": "N/A",
"date_of_birth": null,
"relationship_status": null,
"fav_quote": null,
"best_achievement": null,
"experience": null,
"skills": null,
"height": null,
"weight": null,
"about": null
}
]
Here is my modal class used for json to POJO.
public class UserAboutModel {
#SerializedName("uuid")
#Expose
private String uuid;
#SerializedName("first_name")
#Expose
private String firstName;
#SerializedName("last_name")
#Expose
private String lastName;
#SerializedName("title")
#Expose
private String title;
#SerializedName("gender")
#Expose
private String gender;
#SerializedName("date_of_birth")
#Expose
private String dateOfBirth;
#SerializedName("relationship_status")
#Expose
private String relationshipStatus;
#SerializedName("fav_quote")
#Expose
private String favQuote;
#SerializedName("best_achievement")
#Expose
private String bestAchievement;
#SerializedName("experience")
#Expose
private String experience;
#SerializedName("skills")
#Expose
private String skills;
#SerializedName("about")
#Expose
private String about;
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getRelationshipStatus() {
return relationshipStatus;
}
public void setRelationshipStatus(String relationshipStatus) {
this.relationshipStatus = relationshipStatus;
}
public String getFavQuote() {
return favQuote;
}
public void setFavQuote(String favQuote) {
this.favQuote = favQuote;
}
public String getBestAchievement() {
return bestAchievement;
}
public void setBestAchievement(String bestAchievement) {
this.bestAchievement = bestAchievement;
}
public String getExperience() {
return experience;
}
public void setExperience(String experience) {
this.experience = experience;
}
public String getSkills() {
return skills;
}
public void setSkills(String skills) {
this.skills = skills;
}
public String getAbout() {
return about;
}
public void setAbout(String about) {
this.about = about;
}
}
Here I am calling the method to get the response.
private void getUserAbout() {
apiInterface = APIClient.getClient().create(ApiInterface.class);
SharedPreferences sp = getSharedPreferences("UserData", Context.MODE_PRIVATE);
String token = sp.getString("User_Token", "");
Log.v("working", "working");
Call<UserAboutModel> call = apiInterface.userAboutBasic(currentUserUuid, "Bearer " + token);
call.enqueue(new Callback<UserAboutModel>() {
#Override
public void onResponse(Call<UserAboutModel> call, Response<UserAboutModel> response) {
if (response.isSuccessful()) {
String name = response.body().getFirstName() + " " + response.body().getLastName();
SharedPreferences pref = getSharedPreferences("UserAbout", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
Log.v("NAme", name);
Log.v("Title", response.body().getTitle());
editor.putString("UserName", name);
editor.putString("UserTitle", response.body().getTitle());
editor.putString("UserDOB", response.body().getDateOfBirth());
editor.putString("UserFAvQuote", response.body().getFavQuote());
editor.putString("UserSkill", response.body().getSkills());
editor.putString("UserGender", response.body().getGender());
editor.putString("UserRelationshipStatus", response.body().getRelationshipStatus());
editor.putString("UserExperience", response.body().getExperience());
editor.putString("UserBestAchievment", response.body().getBestAchievement());
editor.putString("UserCategory", primarySports.getText().toString());
editor.putString("UserSports", response.body().getExperience());
editor.apply();
} else {
try {
JSONObject jObjError = new JSONObject(response.errorBody().string());
Toast.makeText(getApplicationContext(), jObjError.getString("message"), Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onFailure(Call<UserAboutModel> call, Throwable t) {
call.cancel();
Log.d("TAG", t.toString());
}
});
}
And here is the log details
D/OkHttp: [{"uuid":"12e26270-b506-11e9-ad81-5f542bb63d66","first_name":"Nohar","last_name":"Kumar","title":"Premier League Player","gender":"N\/A","date_of_birth":null,"relationship_status":null,"fav_quote":null,"best_achievement":null,"experience":null,"skills":null,"height":null,"weight":null,"about":null}]
D/TAG: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
Can anyone help me out? How to solve this error?
The response that you are getting from the server is a list of UserAboutModel. However, in your code, you are expecting a single data. I think the function should look like the following.
public void onResponse(Call<UserAboutModel> call, Response<List<UserAboutModel>> response) {
// Now take the first element from the response list
// and then do the rest of your work
}
Instead of Response<UserAboutModel> use a Response<List<UserAboutModel>> so that it tells the function to expect a list of UserAboutModel.
Hope that helps!
I am consuming an API about cryptocurrency news called CryptoCompare.
My problem is that I can't detect what my code error is.
The error is as follows -> com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 70 path $.Data
I copy the Json and my two classes to help me find the solution.
Json:
{
"Type": 100,
"Message": "News list successfully returned",
"Promoted": [
],
"Data": [
{
"id": "2940487",
"guid": "https://cointelegraph.com/news/australian-hacker-pleads-guilty-to-stealing-450-000-in-xrp-last-year",
"published_on": 1566590880,
"imageurl": "https://images.cryptocompare.com/news/cointelegraph/dj0O90McM86.png",
"title": "Australian Hacker Pleads Guilty to Stealing $450,000 in XRP Last Year",
"url": "https://cointelegraph.com/news/australian-hacker-pleads-guilty-to-stealing-450-000-in-xrp-last-year",
"source": "cointelegraph",
"body": "An Australian woman has pleaded guilty to stealing $450,000 in XRP",
"tags": "Altcoin|Australia|Fraud|Hackers|XRP|Tokens|Police",
"categories": "XRP|ICO|Altcoin",
"upvotes": "0",
"downvotes": "0",
"lang": "EN",
"source_info": {
"name": "CoinTelegraph",
"lang": "EN",
"img": "https://images.cryptocompare.com/news/default/cointelegraph.png"
}
},
]
Link of Api -> https://min-api.cryptocompare.com/data/v2/news/?lang=EN
Java Class News:
public class News {
#SerializedName("Type")
#Expose
private Integer type;
#SerializedName("Message")
#Expose
private String message;
#SerializedName("Data")
#Expose
private List<Article> articles = null;
#SerializedName("HasWarning")
#Expose
private Boolean hasWarning;
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<Article> getArticles() {
return articles;
}
public void setArticles(List<Article> articles) {
this.articles = articles;
}
public Boolean getHasWarning() {
return hasWarning;
}
public void setHasWarning(Boolean hasWarning) {
this.hasWarning = hasWarning;
}
Java Class Article:
public class Article {
#SerializedName("id")
#Expose
private String id;
#SerializedName("guid")
#Expose
private String guid;
#SerializedName("published_on")
#Expose
private Integer publishedOn;
#SerializedName("imageurl")
#Expose
private String imageurl;
#SerializedName("title")
#Expose
private String title;
#SerializedName("url")
#Expose
private String url;
#SerializedName("source")
#Expose
private String source;
#SerializedName("body")
#Expose
private String body;
#SerializedName("tags")
#Expose
private String tags;
#SerializedName("categories")
#Expose
private String categories;
#SerializedName("upvotes")
#Expose
private String upvotes;
#SerializedName("downvotes")
#Expose
private String downvotes;
#SerializedName("lang")
#Expose
private String lang;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getGuid() {
return guid;
}
public void setGuid(String guid) {
this.guid = guid;
}
public Integer getPublishedOn() {
return publishedOn;
}
public void setPublishedOn(Integer publishedOn) {
this.publishedOn = publishedOn;
}
public String getImageurl() {
return imageurl;
}
public void setImageurl(String imageurl) {
this.imageurl = imageurl;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
public String getCategories() {
return categories;
}
public void setCategories(String categories) {
this.categories = categories;
}
public String getUpvotes() {
return upvotes;
}
public void setUpvotes(String upvotes) {
this.upvotes = upvotes;
}
public String getDownvotes() {
return downvotes;
}
public void setDownvotes(String downvotes) {
this.downvotes = downvotes;
}
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang = lang;
}
}
Interface to call Api:
public interface ApiInterface {
#GET("news")
Call<News> getNews(
#Query("lang") String lang,
#Query("api_key") String apiKey,
#Query("lTs") int lTs
);
Retrofit Class Builder
public static Retrofit getApiClient(String BASE_URL){
retrofit = new Retrofit.Builder().baseUrl(BASE_URL)
.client(getUnsafeOkHttpClient().build())
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit;
}
Fragment of Code when i call the api
private void LoadJson(){
swipeRefreshLayout.setRefreshing(true);
final ApiInterface apiInterface = ApiClient.getApiClient(ApiUtils.BASE_URL_NEWS).create(ApiInterface.class);
Call<News> call;
call = apiInterface.getNews("EN", ApiUtils.API_KEY,0);
call.enqueue(new Callback<News>() {
#Override
public void onResponse(Call<News> call, Response<News> response) {
if (response.isSuccessful() && response.body() != null){
articles.addAll(response.body().getArticles());
if (articles.size() - response.body().getArticles().size() == 0){
adapterNews.notifyDataSetChanged();
} else {
adapterNews.notifyItemRangeInserted(articles.size() - response.body().getArticles().size(), response.body().getArticles().size());
}
swipeRefreshLayout.setRefreshing(false);
progressBar.setVisibility(View.GONE);
} else {
Toast.makeText(getContext(), "No result", Toast.LENGTH_SHORT).show();
swipeRefreshLayout.setRefreshing(false);
progressBar.setVisibility(View.GONE);
}
}
#Override
public void onFailure(Call<News> call, Throwable t) {
Log.e(TAG, "ERROR API: " + t.getMessage() + " - " + t.getCause());
}
});
}
Any contribution is very helpful.
Thank you
FIXED THE PROBLEM WAS IN THE CALL
I notice that when you try query on api with wrong value like this
https://min-api.cryptocompare.com/data/v2/news/?lang=en
gives you json instead of array for data so this produce error
For fix and test instead of Locale.getDefault().getLanguage() use just "EN" and check the result
also for more help you can use this logging-interceptor