gpt4 book ai didi

php - Retrofit-Callback.onFailure 被称为

转载 作者:行者123 更新时间:2023-11-29 01:26:36 25 4
gpt4 key购买 nike

我正在尝试运行一个简单的测试应用程序来学习 Retrofit。 onFailure 方法总是被调用,请帮助我。我所做的一切如下:

主 Activity

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;
}
}

API服务:

public interface ApiService 
{
@POST("test_retrofit.php")
public Call<ResponseBody> login();
}

test_retrofit.php://位于www目录(在我的电脑上运行wampserver)

<?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);
}
?>

编辑:(在 iagreen 的有用提示之后)

异常(exception)是:

java.net.SocketTimeoutException:10000 毫秒后无法连接到/192.168.1.7(端口 80)

最佳答案

您的设备似乎无法连接到服务器。您是否在测试改造的同一台设备上测试过它?另一种选择是设备位于不同的网络上。 192.168.x.x 是私有(private) IP,所以如果手机不在同一个子网中,它将找不到服务器。或者,事实证明,您需要确保您的防火墙允许连接到您的服务器。

关于php - Retrofit-Callback.onFailure 被称为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33700751/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com