this is my code:
the interface :
public interface LoginAPI {
#GET("LoginCheck/{username}/{password}/{status}")
Call<List<Login>> LoginCheck(#Path("username") String username, #Path("password") String password, #Path("status") String status);
}
the class:
public class Login {
String username;
String password;
String status;
}
the main activity :
private void LoginCheck() {
String baseUrl = "http:192.168.169.3:8889/WebService_Indekost/";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
LoginAPI api = retrofit.create(LoginAPI.class);
Call<List<Login>> result = api.LoginCheck("username", "password", "status");
result.enqueue(new Callback<List<Login>>() {
#Override
public void onResponse(Call<List<Login>> call, Response<List<Login>> response) {
Log.d("test",response.message());
}
#Override
public void onFailure(Call<List<Login>> call, Throwable t) {
Log.d("Fail", "Fail");
}
});
}
when i try to run it, it shows fail instead of the message. note that the response should be in json format. what am i doing wrong here?
As you commented your error Its saying Expected BEGIN_ARRAY but was BEGIN_OBJECT means exactly You tried to treat it as an Array which starts with brackets like
[ .. data
]
But you are not getting a JSON Array, you are getting an Object. So Try changing the API call Call<List<Login>> into Call<Login>. That may work.
Because you use List<Login> to parse the response, so the response should be a JSON array, like following:
[
{"username":"...","password":"...", "status":"..."},
{"username":"...","password":"...", "status":"..."},
{"username":"...","password":"...", "status":"..."}
]
if the server return result is like following:
{"username":"...","password":"...", "status":"..."}
then you should use Call<Login> replace Call<List<Login>> to parse the response, or, you let server to change its response format to correspond client, it depends what you really want.
Related
I am trying to develop clent-server application with Retrofit. My application sends to server json with a string "image" and responses a json with a string with field "name".
My API:
public interface API {
#FormUrlEncoded
#POST("/api/classification/imagenet")
Call<GestureJson> getName(#Body ImageJson json);
}
ImageJson:
public class ImageJson {
public String imageString;
}
NameJson:
public class NameJson {
public int gestureNumber;
}
When user pressed on button in Main Activity MyVoid is called (url is already known):
public void MyVoid() {
String requestUrl = url;
Retrofit retrofit = new Retrofit.Builder()
.addCallAdapterFactory(GsonConverterFactory.create())
.baseUrl(requestUrl)
.build();
API api = retrofit.create(API.class);
ImageJson json = new ImageJson();
json.imageString = image_uri.toString();
Call<GestureJson> call = api.getName(json);
call.enqueue(new Callback<GestureJson>() {
#Override
public void onResponse(Call<GestureJson> call, Response<GestureJson> response) {
if (response.isSuccessful()) {
status = RESPONSE_SUCCESS;
} else {
status = RESPONSE_FAIL;
}
}
#Override
public void onFailure(Call<GestureJson> call, Throwable t) {
}
});
I have three problems:
1) I don't know what's the difference between Retrofit and Retrofit2. What is better to use?
2) .addCallAdapterFactory(GsonConverterFactory.create()) underlined how wrong (in Retorfit and Retrofit2).
3) I can compile application if i delete .addCallAdapterFactory(GsonConverterFactory.create()). But I have a problem:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.opencvproject, PID: 17742
java.lang.IllegalArgumentException: Unable to create converter for class com.example.opencvproject.GestureJson
for method API.getGesture
Retrofit2 is better because Retrofit outdated (last release was on 2014 https://github.com/square/retrofit/releases/tag/parent-1.6.0). Number 2 in name is just a library version.
GsonConverterFactory may be underlined because you did't add dependency com.squareup.retrofit2:converter-gson
If you delete addCallAdapterFactory(GsonConverterFactory.create()) then Retrofit would't know how to deserialize json to objects. GsonConverterFactory use Gson libarary (https://github.com/google/gson) under the hood to deserialize server json responses.
When sending a request in Postman, I get this output:
{
"valid": false,
"reason": "taken",
"msg": "Username has already been taken",
"desc": "That username has been taken. Please choose another."
}
However when doing it using okhttp, I get encoding problems and can't convert the resulting json string to a Java object using gson.
I have this code:
public static void main(String[] args) throws Exception {
TwitterChecker checker = new TwitterChecker();
TwitterJson twitterJson = checker.checkUsername("dogster");
System.out.println(twitterJson.getValid()); //NPE
System.out.println(twitterJson.getReason());
System.out.println("Done");
}
public TwitterJson checkUsername(String username) throws Exception {
HttpUrl.Builder urlBuilder = HttpUrl.parse("https://twitter.com/users/username_available").newBuilder();
urlBuilder.addQueryParameter("username", username);
String url = urlBuilder.build().toString();
Request request = new Request.Builder()
.url(url)
.addHeader("Content-Type", "application/json; charset=utf-8")
.build();
OkHttpClient client = new OkHttpClient();
Call call = client.newCall(request);
Response response = call.execute();
System.out.println(response.body().string());
Gson gson = new Gson();
return gson.fromJson(
response.body().string(), new TypeToken<TwitterJson>() {
}.getType());
}
Which prints this:
{"valid":false,"reason":"taken","msg":"\u0414\u0430\u043d\u043d\u043e\u0435 \u0438\u043c\u044f \u0443\u0436\u0435 \u0437\u0430\u043d\u044f\u0442\u043e","desc":"\u0414\u0430\u043d\u043d\u043e\u0435 \u0438\u043c\u044f \u0443\u0436\u0435 \u0437\u0430\u043d\u044f\u0442\u043e. \u041f\u043e\u0436\u0430\u043b\u0443\u0439\u0441\u0442\u0430, \u0432\u044b\u0431\u0435\u0440\u0438\u0442\u0435 \u0434\u0440\u0443\u0433\u043e\u0435."}
and then throws a NullPointerException when trying to access a twitterJson. Debugger shows that object as being null.
TwitterJson:
#Generated("net.hexar.json2pojo")
#SuppressWarnings("unused")
public class TwitterJson {
#Expose
private String desc;
#Expose
private String msg;
#Expose
private String reason;
#Expose
private Boolean valid;
public String getDesc() {
return desc;
}
public String getMsg() {
return msg;
}
public String getReason() {
return reason;
}
public Boolean getValid() {
return valid;
}
...
How can I fix the encoding issues with okhttp?
It is because the response object can be consumed only once. OKHTTP says that in their documentation. After the execute is invoked, you are calling the response object twice. Store the result of response.body().string() to a variable and then do the convert into GSON.
If I were to use a hello world example...
private void testOkHttpClient() {
OkHttpClient httpClient = new OkHttpClient();
try {
Request request = new Request.Builder()
.url("https://www.google.com")
.build();
Call call = httpClient.newCall(request);
Response response = call.execute();
System.out.println("First time " + response.body().string()); // I get the response
System.out.println("Second time " + response.body().string()); // This will be empty
} catch (IOException e) {
e.printStackTrace();
}
}
The reason it is empty the second time is because the response object can be consumed only once. So you either
Return the response as it is. Do not do a sysOut
System.out.println(response.body().string()); // Instead of doing a sysOut return the value.
Or
Store the value of the response to a JSON then convert it to GSON and then return the value.
EDIT: Concerning Unicode characters. It turned out since my location is not an English-speaking country, the json i was accepting was not in English as well. I added this header:
.addHeader("Accept-Language", Locale.US.getLanguage())
to the request to fix that.
I need to execute post request with retrofit but i have a problem which i can't understand very well. Before trying with code i tested api call with Postman and request look like this:
Here is my android code:
public class API {
private static <T> T builder(Class<T> endpoint) {
return new Retrofit.Builder()
.baseUrl(Utils.API_BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(endpoint);
}
public static AllRequests request() {
return builder(AllRequests.class);
}
}
EDIT request:
#POST("api/android-feedback")
#Headers({"Content-Type: application/x-www-form-urlencoded", "Authorization: F##3FA##Rad!#%!2s"})
Call<String> sendFeedback(#Body FeedbackBody body);
FeedbackBody:
public class FeedbackBody{
private final String email;
private final String feedback;
public FeedbackBody(String email, String feedback){
this.email = email;
this.feedback = feedback;
}
}
And finally i construct the request and wait for response, the problem is that i receive message in onFail method
private void sendFeedbackRequest(){
API.request().sendFeedback(new FeedbackBody("testmeil#meil.com", "test feedback").enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
goToMainActivity();
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Toast.makeText(SplashScreenActivity.this, R.string.try_again_later, Toast.LENGTH_SHORT).show();
}
});
EDIT:
Still not working.. i think i figure it out where can be the problem, because server side wait for simple POST request without Json formatting, i think Retrofit use JSON formatting by default, and if i send POST request and format Body parameters with JSON the server will fail to parse my request, is there any chance to send simple POST request like at POSTMAN without formatting with JSON ?
Php api wait request to be send like this:
$_POST['feedback'] = 'blabla';
$_POST['email'] = 'blabla..';
and if he receive Json format request can't parse it and because of that i receive fail response.
First you need to create request( POJO Class)
public class FeedbackRequest {
public String email;
public String feedback;
}
when you call sendFeedbackRequest() pass the FeedbackRequest like below"
FeedbackRequest req = new FeedbackRequest();
req.email= "email";
req.feedback= "feedback"
sendFeedbackRequest(req)
after that your sendFeedbackRequest() should be like this
private void sendFeedbackRequest(FeedbackRequest request){
API.request().sendFeedback(request).enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
goToMainActivity();
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Toast.makeText(SplashScreenActivity.this, R.string.try_again_later, Toast.LENGTH_SHORT).show();
}
});
And your retrofit request should be like this,
#FormUrlEncoded
#POST("api/android-feedback")
#Headers({"Content-Type: application/json", "Authorization: F31daaw313415"})
Call<String> sendFeedback(#Body FeedbackRequest request);
Now it should work. feel free to ask anything.
You are using a Gson converter factory. It might be easier to create a single object that represents your body, and use that instead of all individual parameters. That way, you should be able to simple follow along with the examples on the Retrofit website.enter link description here
There are also many site that let you generate your Plain Old Java Objects for you, like this one:
E.g. your Api call:
#POST("api/android-feedback")
Call<String> sendFeedback(#Body FeedbackBody feedback);
And your FeedbackBody class:
public class FeedbackBody{
private final String email;
private final String feedback;
public FeedbackBody(String email, String feedback){
this.email = email;
this.feedback = feedback;
}
}
Java:
#POST("/api/android-feedback")
Call<String> sendFeedback(#Body FeedbackBody feedback);
Kotlin:
#POST("/api/android-feedback")
fun sendFeedback(#Body feedback: FeedbackBody): Call<String>
Also, probably you forgot leading slash in the endpoint.
val formBody: RequestBody = FormBody.Builder()
.add("username", LoginRequest.username)
.add("password", LoginRequest.password)
.add("grant_type",LoginRequest.grant_type)
.add("client_id", LoginRequest.client_id)
.add("client_secret", LoginRequest.client_secret)
.add("cleartext", LoginRequest.cleartext)
.build()
#POST(EndPoints.GENERATE_TOKEN_URL)
#Headers("Content-Type: application/x-www-form-urlencoded")
suspend fun getLogin(
#Body formBody: RequestBody
): LoginResponse
I know there are a lot of threads regarding this and i did go through them and also looked into the same Retrofit POST example,but i'm not sure what am i doing wrong in this,lemme know if any
#Multipart
#POST("api/customerdetail")
Call<Array> addUser(#Part("CustomerName") String CustomerName, #Part("CustomerId") String CustomerId, #Part("UserId") String UserId, #Part("VehicleCompanyName") String VehicleCompanyName, #Part("VehicleModelType")String VehicleModelType, #Part("VehicleNumber")String VehicleNumber, #Part("Location")String Location);
//METHOD USED TO CALL
private void simpleMethod() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://endpoint.net/")
.addConverterFactory(GsonConverterFactory.create())
.build();
GetDataService service = retrofit.create(GetDataService.class);
Call<Array> arrayListCall = service.addUser("Peter Jenkins", UUID.randomUUID().toString(),"user2","AUDI","R3","BVZ-009","-55,-93.23"); arrayListCall.enqueue(new Callback<Array>() {
#Override
public void onResponse(Call<Array> call, Response<Array> response) {
Log.e("RESPONSE",response.toString());
}
#Override
public void onFailure(Call<Array> call, Throwable t) {
Log.e("ERROR",t.toString());
} }); }
Works like a Charm in Postman,and uploading an image is not necessary,atleast from the api end
Any inputs would be deeply appreciated
I would really really appreciate any help I can get on this! Sorry for the long question.
I'm creating this android app, where to sign up, users will type in their phone number and submit it, to get a verification code via text message.
I have worked off of this tutorial:
https://code.tutsplus.com/tutorials/sending-data-with-retrofit-2-http-client-for-android--cms-27845
I have reduced the 2 fields in their app to one field - one text field for a phone number, and a submit button below. This phone number is to be sent to the API.
I'm really new to Retrofit, and I've been trying for a while now to successfully send a call to the API. I have tested the API call by using the 'Postman' desktop app, and the API is alive and responding...I've just not been able to form a valid request to send to the API.
The JSON schema our API guy designed...for this activity needs just one string, the phone number:
{
"phone_number": "string"
}
and then if it is a valid phone number and the user isn't in the database, you get back a 200 response
{
"message": "string"
}
OR you can get back a 400 response from the API
{
"error": "string",
"description": "string"
}
My retrofit interface, called APIService.java looks like this:
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.Body;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
public interface APIService {
#POST("/verifications/signup/send")
#FormUrlEncoded
Call<Post> sendPhoneNumber(#Field("phone_number") String phone_number);
}
I am really new to retrofit2, and above, I can sense one issue, which I don't know how to solve. From the API schema I was given, this one parameter I sent to the API should be 'body'....not 'field'. Maybe in retrofit #Body...I am not too sure how to implement that in this java file above.
Now, what I did below might be really stupid...I don't understand how retrofit java 'model' classes should be made. I followed one tutorial that modeled the class after the RESPONSE, rather than the data call. So, I modified their Post class (which is what I called my ?JSON object to send a single phone number). So my Post class looks like this:
public class Post {
#SerializedName("message")
#Expose
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
#Override
public String toString() {
//return "Post{" + "message = " + message + '}';
return "This is a return message string";
}
}
Honestly, I think what I've done might be totally wrong, but I am not sure how to design the object(Post) class, considering I don't even know what this class will be used for...except getting the response back?
public class MainActivity extends Activity {
private TextView mResponseTv;
private APIService mAPIService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText phoneNumberEt = (EditText)
findViewById(R.id.et_phoneNumber);
Button submitBtn = (Button) findViewById(R.id.btn_submit);
mResponseTv = (TextView) findViewById(R.id.tv_response);
mAPIService = ApiUtils.getAPIService();
submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String phoneNumber = phoneNumberEt.getText().toString().trim();
if (!TextUtils.isEmpty(phoneNumber)) {
sendPost(phoneNumber);
}
}
});
}
public void sendPost(String phone_number) {
mAPIService.sendPhoneNumber(phone_number).enqueue(new Callback<Post>() {
#Override
public void onResponse(Call<Post> call, Response<Post> response) {
int statusCode = response.code();
if (response.isSuccessful()) {
showResponse("Response code is " + statusCode + ". Submitted successfully to API - " + response.body().toString());
Log.i(TAG, "post submitted to API." + response.body().toString());
}
}
#Override
public void onFailure(Call<Post> call, Throwable t) {
showResponse("Unable to submit post to API.");
Log.e(TAG, "Unable to submit post to API.");
}
});
}
public void showResponse(String response) {
if (mResponseTv.getVisibility() == View.GONE) {
mResponseTv.setVisibility(View.VISIBLE);
}
mResponseTv.setText(response);
}
}
My other files are pretty much exactly like the files in the tutorial link above. That's what I modified to get to my simple one text field version.
When I am able to get this to contact the API, and I can read the response, then I'll incorporate this into the real app I'm working on.
For now, the app compliles, and runs on my phone(and emulator too). When I submit the phone number, the text field below the submit button doesn't show any message like it should...so I know for sure that theres a problem once
mAPIService.sendPhoneNumber(phone_number).enqueue(new Callback<Post>() {
#Override
public void onResponse(Call<Post> call, Response<Post> response)
{
is reached in MainActivity.
I think that this api requires parameters in JsonObject. so try this
In your APIService
#POST("/verifications/signup/send")
Call<JsonObject> sendPhoneNumber(#Body JsonObject phone_number);
And when sending data use this
JsonObject object=new JsonObject();
object.addProperty("phone_number",yourPhoneNumber);
and in your send post method
mAPIService.sendPhoneNumber(object).enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
int statusCode = response.code();
if (response.isSuccessful()) {
showResponse("Response code is " + statusCode + ". Submitted successfully to API - " + response.body().toString());
Log.i(TAG, "post submitted to API." + response.body().toString());
}
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
showResponse("Unable to submit post to API.");
Log.e(TAG, "Unable to submit post to API.");
}
});
}
Please try and let me know if it is working.
According to the JSON schema with the phone number, you need to pass the phone number in the body of the API. Instead of using a #Field annotation, use a #Body annotation where the parameter will be an instance of the RequestBody class.
#Field documentation https://square.github.io/retrofit/2.x/retrofit/retrofit2/http/Field.html
Create the new RequestBody class with field phone number.
public class RequestBody {
#Expose
#SerializedName("phone_number")
private String phoneNumber;
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getPhoneNumber() {
return phoneNumber;
}
From the activity when you want to pass the phone number, create an object of the RequestBody class, pass the phone number in the setPhoneNumber() method. Then pass this object in the APIService as a parameter.
In MainActivity.class,
public void sendPost(String phone_number) {
RequestBody requestBody = new RequestBody();
requestBody.setPhoneNumber(phone_number);
mAPIService.sendPhoneNumber(requestBody).enqueue(new Callback<Post>() {
#Override
public void onResponse(Call<Post> call, Response<Post> response)
{
Your APIService will thus look like
public interface APIService {
#POST("/verifications/signup/send")
#FormUrlEncoded
Call<Post> sendPhoneNumber(#Body RequestBody requestBody);
}