首页 > 解决方案 > How can I connect from my Android application to WebApi?

问题描述

I have an WebApi Application and I serialized my data to PC's localhost. I want to see that datas on My Android application. And i wrote an application with okhttp3 library. But its didnt work, when i replace my url with a real url for example: coindesk's api url its working well. what is interesting is that when i writing my localhost address its dont throwing any error, its just closing application on my phone. Here my codes:

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

            }
        });
    });

Here my Json Datas:

Here my Json Datas:

标签: androidjsonasp.net-web-apideserializationokhttp3

解决方案


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

第 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然后应用程序将正常工作。


推荐阅读