2016-10-05 3 views
1

나는 okhttp을 배우고 있으며 내 컴퓨터 또는 Android 장치에서 로컬 json 파일로 테스트를 만들고 싶다. 하지만 함수를 호출하는 URL 문자열로 로컬 파일에 액세스하는 방법을 모르겠습니다. 이처럼 :okhttp로 로컬 테스트하는 방법

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

문자열 URL = "파일 : //"+ testJson.getAbsoluthePath(); 그러나 나는 okhttp가 당신의 시도를 존중하지 않을 것이라고 생각합니다. – greenapps

+1

로컬 테스트를 수행하려면 NanoHttpD와 같은 로컬 웹 서버를 설치하여 파일을 제공하십시오. 플레이 스토어에서 사용할 수있는 웹 서버도 있습니다. – greenapps

+0

@greenapps NanoHttpD와 MockWebServer의 차이점은 무엇입니까? –

답변

2

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/"); 
0

글쎄, 당신은 몇 가지 인터페이스가 추상적 인 당신의 HTTP 클라이언트에있는 두 개의 구현 생성 - 하나를 사용하여 OkHTTP하고 다른 - 단순히 파일을 읽는.

관련 문제