运行retrofit 2.3的我的Android应用程序,当我给它一个带有服务器IP地址的URL时,我不会将我的GET请求发送到我的HTTP服务器。
当我在笔记本电脑,手机或Android工作室模拟器上的浏览器中尝试使用URL时,我的服务器得到了正确的响应。
所以我添加了一个okHttp拦截器记录器,所以我知道网络上发生了什么。它会在日志中打印出来:
okHttp log
D/OkHttp: --> GET https://IP/stuffworks?a=7u http/1.1
D/OkHttp: --> END GET
D/OkHttp: <-- HTTP FAILED: java.net.SocketTimeoutException: connect timed out
这是我在Android应用程序中的实现(当测试call.enqueue总是转到onFailure和Toasts&#34;错误:(&#34;
//Retrofit network method
private void beemMeUp(String ipAdress, String attributes)
{
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
// set your desired log level
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(logging);
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl("https://" + ipAdress + "/")
.client(httpClient.build())
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
SiloClient client = retrofit.create(SiloClient.class);
Call<SiloSensorReport> call = client.report(attributes);
Toast.makeText(this, "https://" + ipAdress + "/" + attributes,
Toast.LENGTH_SHORT).show();
call.enqueue(new Callback<SiloSensorReport>() {
@Override
public void onResponse(Call<SiloSensorReport> call,
Response<SiloSensorReport> response)
{
SiloSensorReport repos = response.body();
textView.append(repos.toString());
Toast.makeText(MainActivity.this, "success :)",
Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Call<SiloSensorReport> call, Throwable t)
{
Toast.makeText(MainActivity.this, "error :(",
Toast.LENGTH_SHORT).show();
}
});
}
}
地址应该是:
http://IPaddress/attribute
例如:
http://123.45.67.12/stuffworks?works=true&value=87
我的服务器代码
server.on("/stuffworks", stuffHandler);
void stuffHandler()
{
Serial.println("User requesting stuffworks page!");
String message = "";
for (int i = 0; i < server.args(); i++)
{
Serial.print(server.argName(i));
Serial.print(": ");
Serial.println(server.arg(i));
message += server.argName(i) + ": " + server.arg(i);
message += "<br>";
}
server.send(200, "text/plain", "it works<br>" + message);
}
P.S。 更改URL以使用http://而不是https://我看到我的服务器打印它得到了一个GET请求,并在使用okHttp记录器捕获的客户端上得到了回复。
D/OkHttp: --> GET http://192.168.43.223/stuffworks?a=val http/1.1
D/OkHttp: --> END GET
D/OkHttp: <-- 200 OK http://192.168.43.223/stuffworks?a=val (50ms)
D/OkHttp: Content-Type: text/plain
D/OkHttp: Content-Length: 22
D/OkHttp: Connection: close
D/OkHttp: it works, a: val
D/OkHttp: <-- END HTTP (22-byte body)`
但是我仍然有一个问题,call.enqueue总是转到onFailure并打印错误:(即使我得到了服务器响应