【发布时间】:2019-08-01 05:17:12
【问题描述】:
我有一个WebApi 应用程序,我将我的数据序列化到PC 的localhost。
我想在我的 Android 应用程序上查看这些数据。我用okhttp3 库编写了一个应用程序。但是它没有用,当我用真实的 url 替换我的 url 时,例如:coindesk 的 api url 运行良好。有趣的是,当我写我的本地主机地址时,它不会抛出任何错误,它只是关闭我手机上的应用程序。这是我的代码:
public class MainActivity extends AppCompatActivity {
private TextView mTextViewResult;
private Button ExecuteButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextViewResult = findViewById(R.id.text_wiev_result);
ExecuteButton = findViewById(R.id.btnCallMethod);
OkHttpClient client = new OkHttpClient();
String url = "https://api.coindesk.com/v1/bpi/currentprice.json";
//String url = "localhost:59085/api/Students";
ExecuteButton.setOnClickListener(v -> {
Request request = new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if(response.isSuccessful())
{
final String myResponse = response.body().string();
MainActivity.this.runOnUiThread(() -> mTextViewResult.setText(myResponse));
}
}
});
});
这是我的 Json 数据:
【问题讨论】:
-
你能显示
localhost:59085/api/Students端点返回的内容吗? -
可能您连接的是 3G 而不是无线路由器,因此您无法访问本地主机
-
@MichałZiober 帖子已更新。
-
JSON看起来是有效的。有什么例外。你也可以显示StackTrace吗? -
@AntonMakov 它不适用于模拟器。
标签: android json asp.net-web-api deserialization okhttp3