My friend coded an API and i have to code the frontend for it on Android. But the json won't arrive. I know that my code works because i testet it on 3 diffrent testers and his api also works. He also testet it a few times. But if i send something to no data will arive. The request arrives but not the data. The response also works but it always says that the Strings are null. I host the api on my own computer. Could it be, that the Virtual Device can't send anything to the pc it is hosted on? I hope someone can help me.
here is my code:
MainActivity
public void post(String pswd, String name){
TextView textViewResult = findViewById(R.id.responses);
Post post = new Post(name,pswd);
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(loggingInterceptor)
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://localhost:5000")
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build();
API api = retrofit.create(API.class);
Call<Post> call = api.createPost(post);
call.enqueue(new Callback<Post>() {
@Override
public void onResponse(Call<Post> call, Response<Post> response) {
if(!response.isSuccessful()){
textViewResult.setText("Code: " + response.code());
return;
}
Post postResponse = response.body();
String content = "";
content += "Code: " + response.code() + "\n";
content += "token: " + postResponse.getToken() + "\n";
content+= "msg: " +postResponse.getMsg();
Endcontent = content;
}
@Override
public void onFailure(Call<Post> call, Throwable t) {
Endcontent = t.getMessage();
}
});
}
Api:
import java.util.List;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
public interface API {
@GET("posts")
Call<List<Get>> getPosts();
@POST("api/gen_token")
Call<Post> createPost(@Body Post post);
}
and the Post:
public class Post {
private String name;
private String pswd;
private String token;
private String msg;
public Post(String name, String pswd) {
this.name = name;
this.pswd = pswd;
}
public String getPswd() {
return pswd;
}
public String getMsg(){
return msg;
}
public String getName() {
return name;
}
public String getToken() {
return token;
}
}
check string name and string pswd value where you have assigned them