@Override
protected void onPostExecute(String ip) {
if (ip != null) {
Toast.makeText(MainActivity.this, Your public IP is: + ip, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, Failed to get public IP, Toast.LENGTH_SHORT).show();
}
}
}.execute();
}
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(https://api.ipify.org/)
.addConverterFactory(ScalarsConverterFactory.create())
.build();
IpService service = retrofit.create(IpService.class);
service.getPublicIp().enqueue(new Callback<String() {
@Override
public void onResponse(Call<String call, Response<String response) {
if (response.isSuccessful()) {
Toast.makeText(MainActivity.this, Your public IP is: + response.body(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, Failed to get public IP, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<String call, Throwable t) {
Toast.makeText(MainActivity.this, Failed to get public IP, Toast.LENGTH_SHORT).show();
}
});
}
}
注意事项
1、权限:确保你的应用有互联网访问权限。
xml
<uses-permission android:name=android.permission.INTERNET /