如何从我的Android应用程序连接到Web Api?

问题描述 投票:0回答:1

我有一个WebApi应用程序,我将我的数据序列化到PC的localhost。我想在My Android应用程序上看到该数据。我用okhttp3库写了一个应用程序。但它没有用,当我用一个真实的网址替换我的网址时:例如:coindesk的api url工作得很好。有趣的是,当我写我的localhost地址时,它不会抛出任何错误,它只是在我的手机上关闭应用程序。这是我的代码:

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数据:

Here my Json Datas:

android json asp.net-web-api deserialization okhttp3
1个回答
0
投票

最后我自己解决了我的问题。老实说,有必要通过很多步骤来解决这个问题。我会一步一步说。

步骤1:打开Windows Defender - >防火墙和网络保护 - >通用网络 - >关闭此保护。

步骤2:安装Jexus Manager,打开它并转到您的电脑名称下的站点选项卡,然后右键单击并添加网站。提供网站名称,然后在物理路径下选择您的Web应用程序路径。给一个端口,例如61508.对于主机名使用127.0.0.1,对于IP地址,请使用您的IPv4地址,然后单击确定按钮。

第3步:在左侧单击您的网站名称,然后在打开的区域右键单击,然后转到 - >管理网站 - >开始。然后单击管理网站 - >浏览并检查您的网站是否运行良好。

第4步:现在打开android并将您当前的URL设置为:http://10.0.2.2:61508/api/Students然后应用程序将运行良好。

© www.soinside.com 2019 - 2024. All rights reserved.