Reputation: 33
I am learning okhttp and I want to make a test with local json file in my computer or android device. But I don't know how to access local file as url string to call the function. Like this:
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);
}
}
Upvotes: 3
Views: 6931
Reputation: 13488
You can use MockWebServer to serve content you load from a file.
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/");
Upvotes: 9
Reputation: 3282
Well, you have to abstract your http client by some interface and create two implementation - one using OkHTTP and another - simply reading file.
Upvotes: 1