Search in sources :

Example 21 with ParseHttpResponse

use of com.parse.http.ParseHttpResponse in project Parse-SDK-Android by ParsePlatform.

the class ParseOkHttpClient method getResponse.

@Override
/* package */
ParseHttpResponse getResponse(Response okHttpResponse) throws IOException {
    // Status code
    int statusCode = okHttpResponse.code();
    // Content
    InputStream content = okHttpResponse.body().byteStream();
    // Total size
    int totalSize = (int) okHttpResponse.body().contentLength();
    // Reason phrase
    String reasonPhrase = okHttpResponse.message();
    // Headers
    Map<String, String> headers = new HashMap<>();
    for (String name : okHttpResponse.headers().names()) {
        headers.put(name, okHttpResponse.header(name));
    }
    // Content type
    String contentType = null;
    ResponseBody body = okHttpResponse.body();
    if (body != null && body.contentType() != null) {
        contentType = body.contentType().toString();
    }
    return new ParseHttpResponse.Builder().setStatusCode(statusCode).setContent(content).setTotalSize(totalSize).setReasonPhrase(reasonPhrase).setHeaders(headers).setContentType(contentType).build();
}
Also used : HashMap(java.util.HashMap) InputStream(java.io.InputStream) ResponseBody(okhttp3.ResponseBody) ParseHttpResponse(com.parse.http.ParseHttpResponse)

Example 22 with ParseHttpResponse

use of com.parse.http.ParseHttpResponse in project Parse-SDK-Android by ParsePlatform.

the class ParseOkHttpClient method addExternalInterceptor.

/**
   * For OKHttpClient, since it does not expose any interface for us to check the raw response
   * stream, we have to use OKHttp networkInterceptors. Instead of using our own interceptor list,
   * we use OKHttp inner interceptor list.
   * @param parseNetworkInterceptor
   */
@Override
/* package */
void addExternalInterceptor(final ParseNetworkInterceptor parseNetworkInterceptor) {
    OkHttpClient.Builder builder = okHttpClient.newBuilder();
    builder.networkInterceptors().add(new Interceptor() {

        @Override
        public Response intercept(final Chain okHttpChain) throws IOException {
            Request okHttpRequest = okHttpChain.request();
            // Transfer OkHttpRequest to ParseHttpRequest
            final ParseHttpRequest parseRequest = getParseHttpRequest(okHttpRequest);
            // Capture OkHttpResponse
            final Capture<Response> okHttpResponseCapture = new Capture<>();
            final ParseHttpResponse parseResponse = parseNetworkInterceptor.intercept(new ParseNetworkInterceptor.Chain() {

                @Override
                public ParseHttpRequest getRequest() {
                    return parseRequest;
                }

                @Override
                public ParseHttpResponse proceed(ParseHttpRequest parseRequest) throws IOException {
                    // Use OKHttpClient to send request
                    Request okHttpRequest = ParseOkHttpClient.this.getRequest(parseRequest);
                    Response okHttpResponse = okHttpChain.proceed(okHttpRequest);
                    okHttpResponseCapture.set(okHttpResponse);
                    return getResponse(okHttpResponse);
                }
            });
            final Response okHttpResponse = okHttpResponseCapture.get();
            // Ideally we should build newOkHttpResponse only based on parseResponse, however
            // ParseHttpResponse does not have all the info we need to build the newOkHttpResponse, so
            // we rely on the okHttpResponse to generate the builder and change the necessary info
            // inside
            Response.Builder newOkHttpResponseBuilder = okHttpResponse.newBuilder();
            // Set status
            newOkHttpResponseBuilder.code(parseResponse.getStatusCode()).message(parseResponse.getReasonPhrase());
            // Set headers
            if (parseResponse.getAllHeaders() != null) {
                for (Map.Entry<String, String> entry : parseResponse.getAllHeaders().entrySet()) {
                    newOkHttpResponseBuilder.header(entry.getKey(), entry.getValue());
                }
            }
            // Set body
            newOkHttpResponseBuilder.body(new ResponseBody() {

                @Override
                public MediaType contentType() {
                    if (parseResponse.getContentType() == null) {
                        return null;
                    }
                    return MediaType.parse(parseResponse.getContentType());
                }

                @Override
                public long contentLength() {
                    return parseResponse.getTotalSize();
                }

                @Override
                public BufferedSource source() {
                    // interceptor.
                    if (parseResponse.getContent() == null) {
                        return null;
                    }
                    return Okio.buffer(Okio.source(parseResponse.getContent()));
                }
            });
            return newOkHttpResponseBuilder.build();
        }
    });
    okHttpClient = builder.build();
}
Also used : ParseHttpRequest(com.parse.http.ParseHttpRequest) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) ParseHttpRequest(com.parse.http.ParseHttpRequest) IOException(java.io.IOException) Capture(bolts.Capture) ResponseBody(okhttp3.ResponseBody) Response(okhttp3.Response) ParseHttpResponse(com.parse.http.ParseHttpResponse) Interceptor(okhttp3.Interceptor) ParseNetworkInterceptor(com.parse.http.ParseNetworkInterceptor) ParseHttpResponse(com.parse.http.ParseHttpResponse)

Example 23 with ParseHttpResponse

use of com.parse.http.ParseHttpResponse in project Parse-SDK-Android by ParsePlatform.

the class ParseDecompressInterceptorTest method testDecompressInterceptorWithNotGZIPResponse.

@Test
public void testDecompressInterceptorWithNotGZIPResponse() throws Exception {
    ParseDecompressInterceptor interceptor = new ParseDecompressInterceptor();
    final String responseContent = "content";
    ParseHttpResponse interceptedResponse = interceptor.intercept(new ParseNetworkInterceptor.Chain() {

        @Override
        public ParseHttpRequest getRequest() {
            // Generate test request
            return new ParseHttpRequest.Builder().setUrl("www.parse.com").setMethod(ParseHttpRequest.Method.GET).build();
        }

        @Override
        public ParseHttpResponse proceed(ParseHttpRequest request) throws IOException {
            // Generate test response
            return new ParseHttpResponse.Builder().setStatusCode(200).setTotalSize(responseContent.length()).setReasonPhrase("Success").setContentType("text/plain").setContent(new ByteArrayInputStream(responseContent.getBytes())).build();
        }
    });
    // Verify response is correct
    assertEquals(200, interceptedResponse.getStatusCode());
    assertEquals(responseContent.length(), interceptedResponse.getTotalSize());
    assertEquals("Success", interceptedResponse.getReasonPhrase());
    assertEquals("text/plain", interceptedResponse.getContentType());
    byte[] content = ParseIOUtils.toByteArray(interceptedResponse.getContent());
    assertArrayEquals(responseContent.getBytes(), content);
}
Also used : ParseHttpRequest(com.parse.http.ParseHttpRequest) ParseNetworkInterceptor(com.parse.http.ParseNetworkInterceptor) ByteArrayInputStream(java.io.ByteArrayInputStream) IOException(java.io.IOException) ParseHttpResponse(com.parse.http.ParseHttpResponse) Test(org.junit.Test)

Example 24 with ParseHttpResponse

use of com.parse.http.ParseHttpResponse in project Parse-SDK-Android by ParsePlatform.

the class ParseDecompressInterceptorTest method testDecompressInterceptorWithGZIPResponse.

@Test
public void testDecompressInterceptorWithGZIPResponse() throws Exception {
    ParseDecompressInterceptor interceptor = new ParseDecompressInterceptor();
    final String responseContent = "content";
    ParseHttpResponse interceptedResponse = interceptor.intercept(new ParseNetworkInterceptor.Chain() {

        @Override
        public ParseHttpRequest getRequest() {
            // Generate test request
            return new ParseHttpRequest.Builder().setUrl("www.parse.com").setMethod(ParseHttpRequest.Method.GET).build();
        }

        @Override
        public ParseHttpResponse proceed(ParseHttpRequest request) throws IOException {
            // Make gzip response content
            ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
            GZIPOutputStream gzipOut = new GZIPOutputStream(byteOut);
            gzipOut.write(responseContent.getBytes());
            gzipOut.close();
            // Make gzip encoding headers
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Encoding", "gzip");
            // Generate test response
            return new ParseHttpResponse.Builder().setStatusCode(200).setTotalSize(byteOut.toByteArray().length).setReasonPhrase("Success").setContentType("text/plain").setContent(new ByteArrayInputStream(byteOut.toByteArray())).setHeaders(headers).build();
        }
    });
    // Verify response is correct
    assertEquals(200, interceptedResponse.getStatusCode());
    assertEquals(-1, interceptedResponse.getTotalSize());
    assertEquals("Success", interceptedResponse.getReasonPhrase());
    assertEquals("text/plain", interceptedResponse.getContentType());
    assertNull(interceptedResponse.getHeader("Content-Encoding"));
    byte[] content = ParseIOUtils.toByteArray(interceptedResponse.getContent());
    assertArrayEquals(responseContent.getBytes(), content);
}
Also used : ParseHttpRequest(com.parse.http.ParseHttpRequest) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ParseNetworkInterceptor(com.parse.http.ParseNetworkInterceptor) GZIPOutputStream(java.util.zip.GZIPOutputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) HashMap(java.util.HashMap) Map(java.util.Map) ParseHttpResponse(com.parse.http.ParseHttpResponse) Test(org.junit.Test)

Example 25 with ParseHttpResponse

use of com.parse.http.ParseHttpResponse in project Parse-SDK-Android by ParsePlatform.

the class ParseFileControllerTest method testFetchAsyncSuccess.

@Test
public void testFetchAsyncSuccess() throws Exception {
    byte[] data = "hello".getBytes();
    ParseHttpResponse mockResponse = new ParseHttpResponse.Builder().setStatusCode(200).setTotalSize((long) data.length).setContent(new ByteArrayInputStream(data)).build();
    ParseHttpClient awsClient = mock(ParseHttpClient.class);
    when(awsClient.execute(any(ParseHttpRequest.class))).thenReturn(mockResponse);
    // Make sure cache dir does not exist
    File root = new File(temporaryFolder.getRoot(), "cache");
    assertFalse(root.exists());
    ParseFileController controller = new ParseFileController(null, root).awsClient(awsClient);
    ParseFile.State state = new ParseFile.State.Builder().name("file_name").url("url").build();
    Task<File> task = controller.fetchAsync(state, null, null, null);
    File result = ParseTaskUtils.wait(task);
    verify(awsClient, times(1)).execute(any(ParseHttpRequest.class));
    assertTrue(result.exists());
    assertEquals("hello", ParseFileUtils.readFileToString(result, "UTF-8"));
    assertFalse(controller.getTempFile(state).exists());
}
Also used : ParseHttpRequest(com.parse.http.ParseHttpRequest) ByteArrayInputStream(java.io.ByteArrayInputStream) File(java.io.File) ParseHttpResponse(com.parse.http.ParseHttpResponse) Test(org.junit.Test)

Aggregations

ParseHttpResponse (com.parse.http.ParseHttpResponse)33 ParseHttpRequest (com.parse.http.ParseHttpRequest)26 Test (org.junit.Test)21 ByteArrayInputStream (java.io.ByteArrayInputStream)20 JSONObject (org.json.JSONObject)12 ParseNetworkInterceptor (com.parse.http.ParseNetworkInterceptor)6 IOException (java.io.IOException)6 HashMap (java.util.HashMap)6 File (java.io.File)4 InputStream (java.io.InputStream)4 MockResponse (okhttp3.mockwebserver.MockResponse)4 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 GZIPOutputStream (java.util.zip.GZIPOutputStream)3 Request (okhttp3.Request)3 Response (okhttp3.Response)3 ResponseBody (okhttp3.ResponseBody)3 Buffer (okio.Buffer)3 Task (bolts.Task)2 ArrayList (java.util.ArrayList)2