我已经使用上述工具设置了一个本地 npm json 服务器,它将返回一个非常简单的 get 请求,就像示例中显示的那样:
{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": { "name": "typicode" }
}
所有权限都已在 Android Studio 中设置了有关 Internet 权限的所有权限(对于这种简单的事情,这就是我所需要的),我正在使用一个小的 okhttp 脚本,该脚本向 url 的内容发出异步请求,这是在一个片段中进行的(因此使用getActivity()
)
public void testAsyncCreate() {
OkHttpClient client = new OkHttpClient();
// no request body necessary since this is going to be handled via the get request as a testing purpose
Request request = new Request.Builder()
.url("http://localhost:3004/create")
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
try {
final String jsonData = response.body().string(); // the exception is caught at this point
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Log.d(TAG,jsonData);
}
});
}catch(IOException e) {
}
}
});
}
只要“用户”单击按钮,就会发出请求。到目前为止,我对此的唯一回应是:
No Network Security Config specified, using patform default
考虑到使用非本地服务器的相同请求(例如对 poke api 发出的获取请求)按预期返回 json 内容的主体,这非常有趣)
在这一点上,我确信这与它是一个本地环境有关。到目前为止,我找不到包含有关本地环境测试详细信息的特定文档。一旦该call.enqueue()
部分开始,调试也会返回 tag=null。