如何使用okhttp进行本地测试

时间:2016-10-05 15:04:45

标签: android okhttp

我正在学习okhttp,我想在我的电脑或Android设备上使用本地json文件进行测试。但我不知道如何访问本地文件作为url字符串来调用该函数。 像这样:

File sdcard = Environment.getExternalStorageDirectory();
File testJson = new File(sdcard, "test.json");
HttpUtils.HttpGet(testJson., mCallback);

public class HttpUtils {
    private static final String TAG = "HttpUtils";

    private static final OkHttpClient mClient = new OkHttpClient();

    public static void HttpGet(String url, Callback callback) {
        //创建一个Request
        final Request request = new Request.Builder()
                .url(url)
                .build();
        //创建一个Call
        Call call = mClient.newCall(request);
        //请求加入调度
        call.enqueue(callback);
    }
}

2 个答案:

答案 0 :(得分:6)

您可以使用MockWebServer来提供从文件加载的内容。

https://github.com/square/okhttp/tree/master/mockwebserver

  MockWebServer server = new MockWebServer();

  // Schedule some responses.
  server.enqueue(new MockResponse().setBody("hello, world!"));
  server.enqueue(new MockResponse().setBody("sup, bra?"));
  server.enqueue(new MockResponse().setBody("yo dog"));

  // Start the server.
  server.start();

  // Ask the server for its URL. You'll need this to make HTTP requests.
  HttpUrl baseUrl = server.url("/v1/chat/");

答案 1 :(得分:1)

好吧,你必须通过某个界面抽象你的http客户端并创建两个实现 - 一个使用OkHTTP,另一个 - 只需读取文件。