Search in sources :

Example 61 with Header

use of okhttp3.internal.http2.Header in project Reader by TheKeeperOfPie.

the class ActivityLogin method loadAccountInfo.

private void loadAccountInfo(final String tokenAuth, final String tokenRefresh, final long timeExpire) {
    Request request = new Request.Builder().url(Reddit.OAUTH_URL + "/api/v1/me").header(Reddit.USER_AGENT, Reddit.CUSTOM_USER_AGENT).header(Reddit.AUTHORIZATION, Reddit.BEARER + tokenAuth).header(Reddit.CONTENT_TYPE, Reddit.CONTENT_TYPE_APP_JSON).get().build();
    reddit.load(request).flatMap(UtilsRx.flatMapWrapError(response -> User.fromJson(ComponentStatic.getObjectMapper().readValue(response, JsonNode.class)))).subscribe(new FinalizingSubscriber<User>() {

        @Override
        public void next(User user) {
            Account account = new Account(user.getName(), Reddit.ACCOUNT_TYPE);
            Intent result = new Intent();
            result.putExtra(AccountManager.KEY_ACCOUNT_NAME, user.getName());
            result.putExtra(AccountManager.KEY_ACCOUNT_TYPE, Reddit.ACCOUNT_TYPE);
            result.putExtra(AccountManager.KEY_AUTHTOKEN, tokenAuth);
            if (getIntent().getBooleanExtra(KEY_IS_NEW_ACCOUNT, false)) {
                Bundle extras = new Bundle();
                extras.putString(KEY_TIME_EXPIRATION, String.valueOf(timeExpire));
                accountManager.addAccountExplicitly(account, tokenRefresh, extras);
                accountManager.setAuthToken(account, Reddit.AUTH_TOKEN_FULL_ACCESS, tokenAuth);
            }
            destroyWebView();
            setAccountAuthenticatorResult(result.getExtras());
            setResult(RESULT_OK, result);
            ActivityLogin.this.finish();
        }
    });
}
Also used : Account(android.accounts.Account) User(com.winsonchiu.reader.data.reddit.User) Bundle(android.os.Bundle) WebResourceRequest(android.webkit.WebResourceRequest) Request(okhttp3.Request) Intent(android.content.Intent)

Example 62 with Header

use of okhttp3.internal.http2.Header in project Parse-SDK-Android by ParsePlatform.

the class ParseHttpClientTest method doSingleParseHttpClientExecuteWithResponse.

private void doSingleParseHttpClientExecuteWithResponse(int responseCode, String responseStatus, String responseContent, ParseHttpClient client) throws Exception {
    MockWebServer server = new MockWebServer();
    // Make mock response
    int responseContentLength = responseContent.length();
    MockResponse mockResponse = new MockResponse().setStatus("HTTP/1.1 " + responseCode + " " + responseStatus).setBody(responseContent);
    // Start mock server
    server.enqueue(mockResponse);
    server.start();
    // Make ParseHttpRequest
    Map<String, String> requestHeaders = new HashMap<>();
    requestHeaders.put("User-Agent", "Parse Android SDK");
    String requestUrl = server.url("/").toString();
    JSONObject json = new JSONObject();
    json.put("key", "value");
    String requestContent = json.toString();
    int requestContentLength = requestContent.length();
    String requestContentType = "application/json";
    ParseHttpRequest parseRequest = new ParseHttpRequest.Builder().setUrl(requestUrl).setMethod(ParseHttpRequest.Method.POST).setBody(new ParseByteArrayHttpBody(requestContent, requestContentType)).setHeaders(requestHeaders).build();
    // Execute request
    ParseHttpResponse parseResponse = client.execute(parseRequest);
    RecordedRequest recordedApacheRequest = server.takeRequest();
    // Verify request method
    assertEquals(ParseHttpRequest.Method.POST.toString(), recordedApacheRequest.getMethod());
    // Verify request headers, since http library automatically adds some headers, we only need to
    // verify all parseRequest headers are in recordedRequest headers.
    Headers recordedApacheHeaders = recordedApacheRequest.getHeaders();
    Set<String> recordedApacheHeadersNames = recordedApacheHeaders.names();
    for (String name : parseRequest.getAllHeaders().keySet()) {
        assertTrue(recordedApacheHeadersNames.contains(name));
        assertEquals(parseRequest.getAllHeaders().get(name), recordedApacheHeaders.get(name));
    }
    // Verify request body
    assertEquals(requestContentLength, recordedApacheRequest.getBodySize());
    assertArrayEquals(requestContent.getBytes(), recordedApacheRequest.getBody().readByteArray());
    // Verify response status code
    assertEquals(responseCode, parseResponse.getStatusCode());
    // Verify response status
    assertEquals(responseStatus, parseResponse.getReasonPhrase());
    // Verify all response header entries' keys and values are not null.
    for (Map.Entry<String, String> entry : parseResponse.getAllHeaders().entrySet()) {
        assertNotNull(entry.getKey());
        assertNotNull(entry.getValue());
    }
    // Verify response body
    byte[] content = ParseIOUtils.toByteArray(parseResponse.getContent());
    assertArrayEquals(responseContent.getBytes(), content);
    // Verify response body size
    assertEquals(responseContentLength, content.length);
    // Shutdown mock server
    server.shutdown();
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) ParseHttpRequest(com.parse.http.ParseHttpRequest) HashMap(java.util.HashMap) Headers(okhttp3.Headers) JSONObject(org.json.JSONObject) MockWebServer(okhttp3.mockwebserver.MockWebServer) HashMap(java.util.HashMap) Map(java.util.Map) ParseHttpResponse(com.parse.http.ParseHttpResponse)

Example 63 with Header

use of okhttp3.internal.http2.Header in project Parse-SDK-Android by ParsePlatform.

the class ParseHttpClientTest method doSingleParseHttpClientExecuteWithGzipResponse.

private void doSingleParseHttpClientExecuteWithGzipResponse(int responseCode, String responseStatus, final String responseContent, ParseHttpClient client) throws Exception {
    MockWebServer server = new MockWebServer();
    // Make mock response
    Buffer buffer = new Buffer();
    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    GZIPOutputStream gzipOut = new GZIPOutputStream(byteOut);
    gzipOut.write(responseContent.getBytes());
    gzipOut.close();
    buffer.write(byteOut.toByteArray());
    MockResponse mockResponse = new MockResponse().setStatus("HTTP/1.1 " + responseCode + " " + responseStatus).setBody(buffer).setHeader("Content-Encoding", "gzip");
    // Start mock server
    server.enqueue(mockResponse);
    server.start();
    // We do not need to add Accept-Encoding header manually, httpClient library should do that.
    String requestUrl = server.url("/").toString();
    ParseHttpRequest parseRequest = new ParseHttpRequest.Builder().setUrl(requestUrl).setMethod(ParseHttpRequest.Method.GET).build();
    // Execute request
    ParseHttpResponse parseResponse = client.execute(parseRequest);
    RecordedRequest recordedRequest = server.takeRequest();
    // Verify request method
    assertEquals(ParseHttpRequest.Method.GET.toString(), recordedRequest.getMethod());
    // Verify request headers
    Headers recordedHeaders = recordedRequest.getHeaders();
    assertEquals("gzip", recordedHeaders.get("Accept-Encoding"));
    // Verify we do not have Content-Encoding header
    assertNull(parseResponse.getHeader("Content-Encoding"));
    // Verify response body
    byte[] content = ParseIOUtils.toByteArray(parseResponse.getContent());
    assertArrayEquals(responseContent.getBytes(), content);
    // Shutdown mock server
    server.shutdown();
}
Also used : Buffer(okio.Buffer) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) ParseHttpRequest(com.parse.http.ParseHttpRequest) GZIPOutputStream(java.util.zip.GZIPOutputStream) Headers(okhttp3.Headers) MockWebServer(okhttp3.mockwebserver.MockWebServer) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ParseHttpResponse(com.parse.http.ParseHttpResponse)

Example 64 with Header

use of okhttp3.internal.http2.Header in project Parse-SDK-Android by ParsePlatform.

the class ParseOkHttpClientTest method testParseOkHttpClientExecuteWithExternalInterceptorAndGZIPResponse.

@Test
public void testParseOkHttpClientExecuteWithExternalInterceptorAndGZIPResponse() throws Exception {
    // Make mock response
    Buffer buffer = new Buffer();
    final ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    GZIPOutputStream gzipOut = new GZIPOutputStream(byteOut);
    gzipOut.write("content".getBytes());
    gzipOut.close();
    buffer.write(byteOut.toByteArray());
    MockResponse mockResponse = new MockResponse().setStatus("HTTP/1.1 " + 201 + " " + "OK").setBody(buffer).setHeader("Content-Encoding", "gzip");
    // Start mock server
    server.enqueue(mockResponse);
    server.start();
    ParseHttpClient client = new ParseOkHttpClient(10000, null);
    final Semaphore done = new Semaphore(0);
    // Add plain interceptor to disable decompress response stream
    client.addExternalInterceptor(new ParseNetworkInterceptor() {

        @Override
        public ParseHttpResponse intercept(Chain chain) throws IOException {
            done.release();
            ParseHttpResponse parseResponse = chain.proceed(chain.getRequest());
            // Make sure the response we get from the interceptor is the raw gzip stream
            byte[] content = ParseIOUtils.toByteArray(parseResponse.getContent());
            assertArrayEquals(byteOut.toByteArray(), content);
            // We need to set a new stream since we have read it
            return new ParseHttpResponse.Builder().setContent(new ByteArrayInputStream(byteOut.toByteArray())).build();
        }
    });
    // We do not need to add Accept-Encoding header manually, httpClient library should do that.
    String requestUrl = server.url("/").toString();
    ParseHttpRequest parseRequest = new ParseHttpRequest.Builder().setUrl(requestUrl).setMethod(ParseHttpRequest.Method.GET).build();
    // Execute request
    ParseHttpResponse parseResponse = client.execute(parseRequest);
    // Make sure the response we get is ungziped by OkHttp library
    byte[] content = ParseIOUtils.toByteArray(parseResponse.getContent());
    assertArrayEquals("content".getBytes(), content);
    // Make sure interceptor is called
    assertTrue(done.tryAcquire(10, TimeUnit.SECONDS));
    server.shutdown();
}
Also used : Buffer(okio.Buffer) MockResponse(okhttp3.mockwebserver.MockResponse) ParseHttpRequest(com.parse.http.ParseHttpRequest) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Semaphore(java.util.concurrent.Semaphore) IOException(java.io.IOException) GZIPOutputStream(java.util.zip.GZIPOutputStream) ParseNetworkInterceptor(com.parse.http.ParseNetworkInterceptor) ByteArrayInputStream(java.io.ByteArrayInputStream) ParseHttpResponse(com.parse.http.ParseHttpResponse) Test(org.junit.Test)

Example 65 with Header

use of okhttp3.internal.http2.Header in project Pokemap by omkarmoghe.

the class NianticManager method loginPTC.

private void loginPTC(final String username, final String password, NianticService.LoginValues values, final LoginListener loginListener) {
    HttpUrl url = HttpUrl.parse(LOGIN_URL).newBuilder().addQueryParameter("lt", values.getLt()).addQueryParameter("execution", values.getExecution()).addQueryParameter("_eventId", "submit").addQueryParameter("username", username).addQueryParameter("password", password).build();
    OkHttpClient client = mClient.newBuilder().followRedirects(false).followSslRedirects(false).build();
    NianticService service = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).client(client).build().create(NianticService.class);
    Callback<NianticService.LoginResponse> loginCallback = new Callback<NianticService.LoginResponse>() {

        @Override
        public void onResponse(Call<NianticService.LoginResponse> call, Response<NianticService.LoginResponse> response) {
            String location = response.headers().get("location");
            if (location != null && location.split("ticket=").length > 0) {
                String ticket = location.split("ticket=")[1];
                requestToken(ticket, loginListener);
            } else {
                Log.e(TAG, "PTC login failed via loginPTC(). There was no location header in response.");
                loginListener.authFailed("Pokemon Trainer Club Login Failed");
            }
        }

        @Override
        public void onFailure(Call<NianticService.LoginResponse> call, Throwable t) {
            t.printStackTrace();
            Log.e(TAG, "PTC login failed via loginPTC(). loginCallback.onFailure() threw: " + t.getMessage());
            loginListener.authFailed("Pokemon Trainer Club Login Failed");
        }
    };
    Call<NianticService.LoginResponse> call = service.login(url.toString());
    call.enqueue(loginCallback);
}
Also used : Call(retrofit2.Call) OkHttpClient(okhttp3.OkHttpClient) HttpUrl(okhttp3.HttpUrl) Response(retrofit2.Response) Retrofit(retrofit2.Retrofit) Callback(retrofit2.Callback)

Aggregations

Test (org.junit.Test)89 MockResponse (okhttp3.mockwebserver.MockResponse)82 Request (okhttp3.Request)75 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)56 Response (okhttp3.Response)54 IOException (java.io.IOException)53 RequestBody (okhttp3.RequestBody)24 OkHttpClient (okhttp3.OkHttpClient)22 Call (okhttp3.Call)20 Callback (okhttp3.Callback)19 Interceptor (okhttp3.Interceptor)14 ResponseBody (okhttp3.ResponseBody)12 FormBody (okhttp3.FormBody)11 Headers (okhttp3.Headers)11 ArrayList (java.util.ArrayList)10 Map (java.util.Map)10 List (java.util.List)9 JSONObject (org.json.JSONObject)8 File (java.io.File)6 HashMap (java.util.HashMap)6