In my app I make post request to the server with a special code inside the body. Then I should get some information in the response. However, I always get the name of the response class.
My request code:
#POST("/accounts/login/vk-oauth2/")
Call<RegistrationProcessCodeResponse> postCode(#Body CodePostRequest code);
My ResponseClass:
public class RegistrationProcessCodeResponse {
private String message;
private String partial_token;
private String phase;
public String getMessage() {
return message;
}
public String getPartial_token() {
return partial_token;
}
public String getPhase() {
return phase;
}
public void setMessage(String message) {
this.message = message;
}
public void setPartial_token(String partial_token) {
this.partial_token = partial_token;
}
public void setPhase(String phase) {
this.phase = phase;
}
}
My request code:
HseAlumniApi hseAlumniApi = HseAlumniApi.retrofit.create(HseAlumniApi.class);
Call<RegistrationProcessCodeResponse> postComment = hseAlumniApi.postCode(codePostRequest);
postComment.enqueue(new Callback<RegistrationProcessCodeResponse>() {
#Override
public void onResponse(Call<RegistrationProcessCodeResponse> call, Response<RegistrationProcessCodeResponse> response) {
Log.d("myLogs", "String.valueOf(response.code())\n" + String.valueOf(response.code()));
Log.d("myLogs", "response.body().toString()\n" + response.body().toString());
if (response.isSuccessful()) {
Log.d("myLogs", "Request succeeded");
}
}
#Override
public void onFailure(Call<RegistrationProcessCodeResponse> call, Throwable t) {
Log.d("myLogs", "Request failed");
}
});
My logs:
D/myLogs: String.valueOf(response.code())
200
D/myLogs: response.body().toString()
com.example.vitaly.hsealumni.RegistrationProcessCodeResponse#498e7e7
D/myLogs: Request succeeded
Response Json:
{
"message": "email needed",
"partial_token": "231445d4fc5a4ed99dccb681942d5d7e",
"phase": 1
}
I really have no idea what to do, help please
public class RegistrationProcessCodeResponse {
private String message;
private String partial_token;
private String phase;
public RegistrationProcessCodeResponse() {
message = "";
partial_token = "";
phase = "";
}
// getters and setters
#Override
public String toString() {
return "RegistrationProcessCodeResponse{" +
"message='" + message + '\'' +
", partial_token='" + partial_token + '\'' +
", phase='" + phase + '\'' +
'}';
}
}
Related
Here is my json URL https://jsonplaceholder.typicode.com/todos I want to display only completed: true is to be strike through, how can I do that?
MainActivity.java
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://jsonplaceholder.typicode.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
JsonPlaceHolderApi jsonPlaceHolderApi = retrofit.create(JsonPlaceHolderApi.class);
Call<List<Post>> call = jsonPlaceHolderApi.getPosts();
call.enqueue(new Callback<List<Post>>() {
#Override
public void onResponse(Call<List<Post>> call, Response<List<Post>> response) {
if (!response.isSuccessful()) {
textresult.setText("Code: " + response.code());
return;
}
List<Post> posts = response.body();
for (Post post : posts) {
String content = "";
content += "User ID: " + post.getUserId() + "\n";
content += "ID: " + post.getId() + "\n";
content += " Title: " + post.getTitle() + "\n";
content += "Completed: " + post.getCompleted() + "\n\n";
textresult.append(content);
if (post.getCompleted().contains("true")) {
textresult.setPaintFlags(textresult.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
}
}
#Override
public void onFailure(Call<List<Post>> call, Throwable t) {
textresult.setText(t.getMessage());
}
});
JsonPlaceHolderApi.java
public interface JsonPlaceHolderApi {
#GET("todos")
Call<List<Post>> getPosts();
}
Post.java
public class Post {
private int userId;
private int id;
private String title;
private String completed;
public int getUserId() {
return userId;
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public String getCompleted() {
return completed;
}
}
When I try to run the above code I got output as image, but I need if completed: true it should be strike.
it is not possible to do setPaintFlags() with custom text better use can use HTML text for your work for you don't need to check "post.complete()", just append all content in a single string and replace your target string (complete: true) with HTML text.
just do it like
String content = "";
for (Post post : posts) {
content += "User ID: " + post.getUserId() + "\n";
content += "ID: " + post.getId() + "\n";
content += " Title: " + post.getTitle() + "\n";
content += "Completed: " + post.getCompleted() + "\n\n";
}
String tempHtmlText = content.replaceAll("Completed: true","<strike>Completed: true</strike>");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
textresult.setText(Html.fromHtml(tempHtmlText , Html.FROM_HTML_MODE_LEGACY));
} else {
textresult.setText(Html.fromHtml(tempHtmlText));
}
or you can use Gson formmater
I have a problem i try to get a message after passing a value to PHP file then how to show the value of massge
from within the php file I tried but I have an error message ,how do I get a message from the php file so that it is the result of the Non or Don message as written in the php file , see my code
// Log.i: msg: error loading from API java.lang.IllegalStateException:Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
// MainActivity class:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// updateList();
post_1();
}
}, 300);
}
public void post_1(){
ApiUtil.getServiceClass().getAllPost("ahmed").enqueue(new Callback<List<ApiObject>>() {
#Override
public void onResponse(Call<List<ApiObject>> call,Response<List<ApiObject>>response) {
if(response.isSuccessful()){
List<ApiObject> postList = response.body();
Log.i("msg", "Returned msg " + response.message().toString());
//Log.i("msg", "Returned count " + postList.size());
}
}
#Override
public void onFailure(Call<List<ApiObject>> call, Throwable t) {
//showErrorMessage();
Log.i("msg", "error loading from API "+t.toString());
}
});
}
// End ;
}
// interface :
public interface RetrofitInterface {
#GET("get.php")
public Call<List<ApiObject>> getAllPost(#Query("name") String user_name);
}
// ApiUtil class :
public class ApiUtil {
private static final String BASE_URL = "http://192.168.1.3/test/";
public static RetrofitInterface getServiceClass(){
return RetrofitAPI.getRetrofit(BASE_URL).create(RetrofitInterface.class);
}
}
// ApiObject class :
public class ApiObject {
#SerializedName("name")
private String name;
#SerializedName("message")
private String message;
public ApiObject(String user_name, String message) {
this.name = user_name;
this.message = message;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
// php file :
<?php
// include Marei DB Class
include 'DB.php';
// get content input and create json object to parse it
$data = file_get_contents("php://input");
$obj = json_decode($data);
// create db instance to use marei db queris
$db = DB::getInstance();
// set type of header response to application/json for respone
header('Content-Type: application/json');
if(!$_GET["name"]) {
print json_encode(['status' => 0, 'message' => 'Username is Non !']);
}else{
print json_encode(['status' => 1, 'message' => 'Username is Don !']);
}
?>
I am trying to send POST Request from Android to Spring via Retrofit from past 2 days. I have tried plenty of solutions regarding this, but nothing seems to be working. So, asking here finally to be able to get some help.
So, i am trying to send a simple Object from Android to Spring via retrofit. From android side i have verified the values sent by me and it gives me correct value.(I have debugged it via Android's debugging mode). But on spring side i got null values.
This is my code ->
function foo() -> from which i am sending my request.
private void foo() {
request.setName1("XYZ");
request.setName2("PQR");
Api.upload(request, new Callback<BasicResponse>() {
#Override
public void onResponse(Call<BasicResponse> call, Response<BasicResponse> response) {
Log.d(TAG, "onResponse: Success" + response.toString());
}
#Override
public void onFailure(Call<BasicResponse> call, Throwable t) {
Log.d(TAG, "onResponse: Failure");
}
});
}
}
my upload Function ->
public static void upload(Request request, Callback<BasicResponse> callback) {
uploadRequest api = retrofit.create(uploadRequest.class);
Call<BasicResponse> call = uploadRequest.uploadCall(POJO);
call.enqueue(callback);
}
This is my UploadRequest Interface ->
public interface uploadRequest{
#POST(UPLOAD_REQUEST)
Call<BasicResponse> uploadCall(#Body POJO pojo);
}
This is My POJO Class
public class POJO {
private String Name1;
private String Name2;
public String getName1() {
return Name1;
}
public void setName1(String name1) {
Name1 = name1;
}
public String getName2() {
return Name2;
}
public void setName2(String name2) {
Name2 = name2;
}
}
And this is my Spring Controller Method
#RequestMapping(value = "/UploadRequest",method = RequestMethod.POST,consumes = "application/json", produces = "application/json")
#ResponseBody
public void UploadImage(#RequestBody POJO pojo,HttpServletRequest request) {
if(pojo!=null){
System.out.println("pojo is not null");
System.out.println(pojo.getName1());
}
else{
System.out.println("null");
}
}
I am getting pojo is not null and inside the pojo.getName1(), the value prints is null.
Edit : Adding BasicResponse Class.
public class BasicResponse {
private boolean success = Boolean.TRUE;
private ErrorCode errorCode;
private String response;
private Integer totalCount;
private String callingUserId;
public BasicResponse() {
super();
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public ErrorCode getErrorCode() {
return errorCode;
}
public void setErrorCode(ErrorCode errorCode) {
this.errorCode = errorCode;
this.success = false;
}
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
public void setResponse(Object response) {
if (response != null) {
this.response = GsonUtils.toGson(response);
}
}
public Integer getTotalCount() {
return totalCount;
}
public void setTotalCount(Integer totalCount) {
this.totalCount = totalCount;
}
public String getCallingUserId() {
return callingUserId;
}
public void setCallingUserId(String callingUserId) {
this.callingUserId = callingUserId;
}
}
Compare the response and your POJO class. The instance variables of your POJO class must be the same as in response. In your case Name1 and Name2. If they are name1, name2 in the response (which means if they do not start with capital letters, etc.), or different, it gives you NullPointerException.
Most likely Name1 and Name2 have different names in json than in your POJO and Jackson, with is used under the hood when you annotate your parameters with #RequestBody can not figure them out, so you get null values. Check out your json.
So I'm trying to implement a publisher/subscriber pattern in JAX-RS however it seems that after the subscriber subscribes the publisher cannot find the subscription.
Server Code:
#GET
#Path("{id}/subscribe")
public void subscribe(#Suspended AsyncResponse asyncResponse, #PathParam("id") Long id) {
if (responses.containsKey(id)) {
responses.get(id).add(asyncResponse);
} else {
List<AsyncResponse> newList = new ArrayList<>();
newList.add(asyncResponse);
responses.put(id, newList);
}
System.out.println(responses.size());
}
#POST
#Path("{id}/publish")
#Consumes(MediaType.TEXT_PLAIN)
public void publish(String message, #PathParam("id") Long id) {
System.out.println(responses.size());
List<AsyncResponse> responseList = responses.get(id);
if (responseList == null) {
return;
}
for (AsyncResponse response : responseList) {
response.resume(message);
}
responseList.clear();
}
Client Code:
public void subscribeToConcertNews(ConcertDTO concertDTO) {
Response response = null;
String url = CONCERT_URL + "/" + concertDTO.getId() + "/subscribe";
ClientBuilder.newClient().target(url)
.request()
.async()
.get(new InvocationCallback<String>() {
#Override
public void completed(String s) {
System.out.println(s);
_client.target(CONCERT_URL + "/" + concertDTO.getId() + "/subscribe")
.request()
.async()
.get(this);
}
#Override
public void failed(Throwable throwable) {
throw new ServiceException("");
}
});
}
public void publishToConcertNews(ConcertDTO concertDTO, String message) {
Response response = _client.target(CONCERT_URL + "/" + concertDTO.getId() + "/publish")
.request()
.post(Entity.entity("News!", MediaType.TEXT_PLAIN));
}
Testing Code:
ConcertDTO concertDTO = new ConcertDTO(1L, "123", new HashSet<>(), new HashMap<>(), new HashSet<>());
_service.subscribeToConcertNews(concertDTO);
_service.publishToConcertNews(concertDTO, "213123");
After the subscription, the size of the map is 1, however news is attempted to be published it reads that the size of the map to hold the responses is 0. So the AsyncResponse stored in the map is disappearing. Any help would be appreciated!
I have one url with request parameter is in JsonFormat like
{"EmailAddress":"user#gmail.com","PassWord":"password"} it's requested parameter.
When i used in POSTMAN then its okey.but when i request with program then that time i got error response. ihave tried till like this please see this snippet.
public class LoginModel {
#SerializedName("EmailAddress")
public String userName;
#SerializedName("PassWord")
public String userPass;
}
#Override
public String toString() {
Log.e("POSTLOGIN_MODEL" , userName+"||"+userPass);
return "{" +
"EmailAddress='" + userName + '\'' +
", PassWord='" + userPass + '\'' +
'}';
}
}
After that i used Interface.
public interface ApiService {
#FormUrlEncoded
#POST("/json/syncreply/AuthenticateUserRequest?")
Call<LoginResponse> LoginService(#Field("EmailAddress") String userName, #Field("PassWord") String userPass, Callback<LoginResponse> callBack);
After that i used to call this interface method through activity.
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(input_username.getText().toString() != null && input_password.getText().toString() != null
&& !input_username.getText().toString().isEmpty() && !input_password.getText().toString().isEmpty()){
LoginModel loginCredentials = new LoginModel();
loginCredentials.userName = "test#gmail.com";
loginCredentials.userPass = "password";
String request = "{\"EmailAddress\":\"raj#gmail.com\"," +
"\"PassWord\":\"pass\"}";
sendPost(loginCredentials);
}else{
Toast.makeText(getApplicationContext() , "Please enter valid Username and Password." , Toast.LENGTH_LONG).show();
}
}
});
public void sendPost(LoginModel name) {
Log.e("TAG","||"+name.userPass+"||"+name.userName);
// mAPIService.savePost(name).enqueue(new Callback<LoginModel>() {
Call<LoginResponse> call = mAPIService.LoginService(name.userName, name.userPass, new Callback<LoginResponse>() {
#Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
Log.e("TAG" , "RESPONSE"+"||"+response.body());
}
#Override
public void onFailure(Call<LoginResponse> call, Throwable t) {
Log.e("TAG" , "FAILURE"+"||"+t.getMessage());
}
});
}
Thanks In Advance.any answer will appriciated.my english is please avoid it.
Hey Rajan use Request body to pass Json
String request = "{\"EmailAddress\":\"raj#gmail.com\"," + "\"PassWord\":\"pass\"}";
RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),request);
#Headers("Content-Type: application/json; charset=utf-8")
#POST("/json/syncreply/AuthenticateUserRequest")
Call<ResponseBody> AuthenticateUserRequest(#Body RequestBody body);
aCall.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
ResponseBody responseBody = response.body();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
First on your rest client interface side change the method like below, instead of taking email and password both seperately take only one ArrayList of String there :
#FormUrlEncoded
#POST(WEBSERVICE_NAME)
Call<ModelClass> methodName(
#Field("parameters" + "[]") ArrayList<String> paramsArrayList
);
Now, convert your arraylist of model class in to JSON string using GSON library like this,
private ArrayList<String> getModelClassArrayinString(ArrayList<ModelClass> arrayList) {
ArrayList<String> arrayListString = new ArrayList<>();
for (int i = 0; i < arrayList.size(); i++) {
arrayListString.add(new Gson().toJson(arrayList.get(i)).toString());
}
return arrayListString;
}
So your final call will be like this :
Call<LoginResponse> call = mAPIService.LoginService(getModelClassArrayinString(arrayListofModelClass), new Callback<LoginResponse>() {
#Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
Log.e("TAG" , "RESPONSE"+"||"+response.body());
}
#Override
public void onFailure(Call<LoginResponse> call, Throwable t) {
Log.e("TAG" , "FAILURE"+"||"+t.getMessage());
}
});