Search in sources :

Example 71 with Headers

use of okhttp3.Headers in project okhttp-OkGo by jeasonlzy.

the class BaseDetailActivity method handleError.

protected void handleError(Call call, Response response) {
    StringBuilder sb;
    if (call != null) {
        requestState.setText("请求失败  请求方式:" + call.request().method() + "\n" + "url:" + call.request().url());
        Headers requestHeadersString = call.request().headers();
        Set<String> requestNames = requestHeadersString.names();
        sb = new StringBuilder();
        for (String name : requestNames) {
            sb.append(name).append(" : ").append(requestHeadersString.get(name)).append("\n");
        }
        requestHeaders.setText(sb.toString());
    } else {
        requestState.setText("--");
        requestHeaders.setText("--");
    }
    responseData.setText("--");
    if (response != null) {
        Headers responseHeadersString = response.headers();
        Set<String> names = responseHeadersString.names();
        sb = new StringBuilder();
        sb.append("stateCode : ").append(response.code()).append("\n");
        for (String name : names) {
            sb.append(name).append(" : ").append(responseHeadersString.get(name)).append("\n");
        }
        responseHeader.setText(sb.toString());
    } else {
        responseHeader.setText("--");
    }
}
Also used : Headers(okhttp3.Headers)

Example 72 with Headers

use of okhttp3.Headers in project okhttp-OkGo by jeasonlzy.

the class BaseDetailActivity method handleResponse.

protected <T> void handleResponse(T data, Call call, Response response) {
    StringBuilder sb;
    if (call != null) {
        requestState.setText("请求成功  请求方式:" + call.request().method() + "\n" + "url:" + call.request().url());
        Headers requestHeadersString = call.request().headers();
        Set<String> requestNames = requestHeadersString.names();
        sb = new StringBuilder();
        for (String name : requestNames) {
            sb.append(name).append(" : ").append(requestHeadersString.get(name)).append("\n");
        }
        requestHeaders.setText(sb.toString());
    } else {
        requestState.setText("--");
        requestHeaders.setText("--");
    }
    if (data == null) {
        responseData.setText("--");
    } else {
        if (data instanceof String) {
            responseData.setText((String) data);
        } else if (data instanceof List) {
            sb = new StringBuilder();
            List list = (List) data;
            for (Object obj : list) {
                sb.append(obj.toString()).append("\n");
            }
            responseData.setText(sb.toString());
        } else if (data instanceof Set) {
            sb = new StringBuilder();
            Set set = (Set) data;
            for (Object obj : set) {
                sb.append(obj.toString()).append("\n");
            }
            responseData.setText(sb.toString());
        } else if (data instanceof Map) {
            sb = new StringBuilder();
            Map map = (Map) data;
            Set keySet = map.keySet();
            for (Object key : keySet) {
                sb.append(key.toString()).append(" : ").append(map.get(key)).append("\n");
            }
            responseData.setText(sb.toString());
        } else if (data instanceof File) {
            File file = (File) data;
            responseData.setText("数据内容即为文件内容\n下载文件路径:" + file.getAbsolutePath());
        } else if (data instanceof Bitmap) {
            responseData.setText("图片的内容即为数据");
        } else {
            responseData.setText(data.toString());
        }
    }
    if (response != null) {
        Headers responseHeadersString = response.headers();
        Set<String> names = responseHeadersString.names();
        sb = new StringBuilder();
        sb.append("url : ").append(response.request().url()).append("\n\n");
        sb.append("stateCode : ").append(response.code()).append("\n");
        for (String name : names) {
            sb.append(name).append(" : ").append(responseHeadersString.get(name)).append("\n");
        }
        responseHeader.setText(sb.toString());
    } else {
        responseHeader.setText("--");
    }
}
Also used : Bitmap(android.graphics.Bitmap) Set(java.util.Set) Headers(okhttp3.Headers) List(java.util.List) Map(java.util.Map) File(java.io.File)

Example 73 with Headers

use of okhttp3.Headers in project okhttp-OkGo by jeasonlzy.

the class HttpLoggingInterceptor method logForResponse.

private Response logForResponse(Response response, long tookMs) {
    Response.Builder builder = response.newBuilder();
    Response clone = builder.build();
    ResponseBody responseBody = clone.body();
    boolean logBody = (printLevel == Level.BODY);
    boolean logHeaders = (printLevel == Level.BODY || printLevel == Level.HEADERS);
    try {
        log("<-- " + clone.code() + ' ' + clone.message() + ' ' + clone.request().url() + " (" + tookMs + "ms)");
        if (logHeaders) {
            Headers headers = clone.headers();
            for (int i = 0, count = headers.size(); i < count; i++) {
                log("\t" + headers.name(i) + ": " + headers.value(i));
            }
            log(" ");
            if (logBody && HttpHeaders.hasBody(clone)) {
                if (isPlaintext(responseBody.contentType())) {
                    String body = responseBody.string();
                    log("\tbody:" + body);
                    responseBody = ResponseBody.create(responseBody.contentType(), body);
                    return response.newBuilder().body(responseBody).build();
                } else {
                    log("\tbody: maybe [file part] , too large too print , ignored!");
                }
            }
        }
    } catch (Exception e) {
        OkLogger.e(e);
    } finally {
        log("<-- END HTTP");
    }
    return response;
}
Also used : Response(okhttp3.Response) HttpHeaders(okhttp3.internal.http.HttpHeaders) Headers(okhttp3.Headers) IOException(java.io.IOException) ResponseBody(okhttp3.ResponseBody)

Example 74 with Headers

use of okhttp3.Headers 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 75 with Headers

use of okhttp3.Headers 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)

Aggregations

Test (org.junit.Test)69 Request (okhttp3.Request)58 Response (okhttp3.Response)53 Headers (okhttp3.Headers)46 IOException (java.io.IOException)34 MockResponse (okhttp3.mockwebserver.MockResponse)33 HttpHeaders (okhttp3.internal.http.HttpHeaders)29 ResponseBody (okhttp3.ResponseBody)27 RequestBody (okhttp3.RequestBody)21 List (java.util.List)19 MediaType (okhttp3.MediaType)16 HashMap (java.util.HashMap)15 Map (java.util.Map)15 ANResponse (com.androidnetworking.common.ANResponse)13 AnalyticsListener (com.androidnetworking.interfaces.AnalyticsListener)13 LinkedHashMap (java.util.LinkedHashMap)13 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)13 Buffer (okio.Buffer)12 ANError (com.androidnetworking.error.ANError)11 HttpURLConnection (java.net.HttpURLConnection)11