I'm trying to run a simple test app for learning Retrofit. The onFailure
method is always called, please help me. All I've done is as follows:
MainActivity
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
method();
}
public void method()
{
final String BASE_URL = "http://192.168.1.7/";
Retrofit retrofit = new Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService service = retrofit.create(ApiService.class);
Call<ResponseBody> call = service.login();
call.enqueue(new Callback<ResponseBody>(){
@Override
public void onResponse(Response<ResponseBody> response, Retrofit retrofit)
{
// TODO Auto-generated method stub
if (response.isSuccess())
{
Log.i("mok","S");
ResponseBody rb = response.body();
}
else
{
Log.i("mok","F");
com.squareup.okhttp.ResponseBody rb = response.errorBody();
}
}
@Override
public void onFailure(Throwable t)
{
Log.i("mok",t.getCause()+"");//This is null
Log.i("mok","T");//This is shown in LogCat
finish();
}
});
}
}
RespnseBody
:
public class ResponseBody
{
private String username;
private String password;
public ResponseBody(String username, String password)
{
this.setUsername(username);
this.setPassword(password);
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
ApiService
:
public interface ApiService
{
@POST("test_retrofit.php")
public Call<ResponseBody> login();
}
test_retrofit.php
: //located at www directory (running wampserver on my computer)
<?php
$response = array("error" => FALSE);
if ( isset($_POST['username']) )
{
$response["username"] = "moker";
$response["password"] = "0107";
echo json_encode($response);
}
else
{
$response["username"] = "mok";
$response["password"] = "107";
echo json_encode($response);
}
?>
Edit: (After iagreen's useful hint)
Exception is:
java.net.SocketTimeoutException: failed to connect to /192.168.1.7 (port 80) after 10000ms