使用 OkHttp 从 Android 项目 (Java) 发送 Http 请求

问题描述

我只是想从我的 Android 项目 (JAVA) 发送一个简单的 GET 请求,看看它是否连接到我的应用程序 (node/express. js) 使用 OkHttp

这是我在主活动

中的OkHttp代码
OkHttpClient client = new OkHttpClient();

Request get = new Request.Builder()
                .url("http://10.0.2.2:3000")
                .build();

client.newCall(get).enqueue(new Callback() {
            @Override
            public void onFailure(Call call,IOException e) {
                e.printstacktrace();
            }
            @Override
            public void onResponse(Call call,Response response) throws IOException {
                try{

                    ResponseBody responseBody=response.body();
                    Log.i("datadatadata",responseBody.string());
                    if(!response.isSuccessful()){
                        throw new IOException("Unexpected code " + response);
                    }
                }
                catch(Exception e){
                    e.printstacktrace();
                }
            }
});

如果我将 url 设置为 *https:\google.com*,请求就会通过(所以 OkHttp 代码工作正常)。

所以我用我的 IPv4 地址:3000 而不是 10.0.2.2:3000 仍然不起作用

这两个地址都可以通过 AVD 浏览器访问 (10.0.2.2:3000 && IPv4:3000)

我知道这是多余的,但这是我的GET Route

app.get("/",(req,res)=>{
    console.log("called called")
    res.sendFile(index.html)
})

我已经在清单文件添加互联网访问权限

 <uses-permission android:name="android.permission.INTERNET" />

所以我不知道我在代码上做错了什么,你们能帮我解决这个问题吗??

更新

放弃了 OkHttp 正在使用这个版本

   implementation 'com.squareup.okhttp3:okhttp:3.12.0'

在我的项目中添加Volley

在清单文件添加了这个

  android:usesCleartextTraffic="true"

从 Android 站点获得代码

// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://10.0.2.2:3000";

// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET,url,new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        // display the first 500 characters of the response string.
        Log.i("response",response);
    }
},new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Log.i("response error",error.getMessage())
    }
});

// Add the request to the RequestQueue.
queue.add(stringRequest);

这行得通!!


我刚刚检查了 OkHttp 库位于

implementation("com.squareup.okhttp3:okhttp:4.9.0")

我可能遇到错误,因为我使用的是过时的版本

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)