com.squareup.okhttp.Headers Java Examples

The following examples show how to use com.squareup.okhttp.Headers. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OkHttpRequest.java    From meiShi with Apache License 2.0 7 votes vote down vote up
protected void appendHeaders(Request.Builder builder, Map<String, String> headers)
{
    if (builder == null)
    {
        throw new IllegalArgumentException("builder can not be empty!");
    }

    Headers.Builder headerBuilder = new Headers.Builder();
    if (headers == null || headers.isEmpty()) return;

    for (String key : headers.keySet())
    {
        headerBuilder.add(key, headers.get(key));
    }
    builder.headers(headerBuilder.build());
}
 
Example #2
Source File: PaginationHeaderParser.java    From octodroid with MIT License 6 votes vote down vote up
public static Pagination parse(Headers headers) {
    if (headers == null) {
        return new Pagination();
    }

    String linksString = headers.get(HEADER_KEY_LINK);
    if (TextUtils.isEmpty(linksString)) {
        return new Pagination(null);
    }

    String[] linkStrings = linksString.split(",");
    if (linkStrings.length == 0) {
        return new Pagination(null);
    }

    Link[] links = new Link[linkStrings.length];
    for (int i = 0; i < links.length; i++) {
        Link link = Link.fromSource(linkStrings[i]);
        links[i] = link;
    }

    return new Pagination(links);
}
 
Example #3
Source File: HttpConnection.java    From tencentcloud-sdk-java with Apache License 2.0 6 votes vote down vote up
public Response postRequest(String url, String body, Headers headers)
    throws TencentCloudSDKException {
  MediaType contentType = MediaType.parse(headers.get("Content-Type"));
  Request request = null;
  try {
    request =
        new Request.Builder()
            .url(url)
            .post(RequestBody.create(contentType, body))
            .headers(headers)
            .build();
  } catch (IllegalArgumentException e) {
    throw new TencentCloudSDKException(e.getClass().getName() + "-" + e.getMessage());
  }

  return this.doRequest(request);
}
 
Example #4
Source File: HttpConnection.java    From tencentcloud-sdk-java with Apache License 2.0 6 votes vote down vote up
public Response postRequest(String url, byte[] body, Headers headers)
    throws TencentCloudSDKException {
  MediaType contentType = MediaType.parse(headers.get("Content-Type"));
  Request request = null;
  try {
    request =
        new Request.Builder()
            .url(url)
            .post(RequestBody.create(contentType, body))
            .headers(headers)
            .build();
  } catch (IllegalArgumentException e) {
    throw new TencentCloudSDKException(e.getClass().getName() + "-" + e.getMessage());
  }

  return this.doRequest(request);
}
 
Example #5
Source File: OkHttpUploadRequest.java    From meiShi with Apache License 2.0 6 votes vote down vote up
@Override
public RequestBody buildRequestBody()
{
    MultipartBuilder builder = new MultipartBuilder()
            .type(MultipartBuilder.FORM);
    addParams(builder, params);

    if (files != null)
    {
        RequestBody fileBody = null;
        for (int i = 0; i < files.length; i++)
        {
            Pair<String, File> filePair = files[i];
            String fileKeyName = filePair.first;
            File file = filePair.second;
            String fileName = file.getName();
            fileBody = RequestBody.create(MediaType.parse(guessMimeType(fileName)), file);
            builder.addPart(Headers.of("Content-Disposition",
                            "form-data; name=\"" + fileKeyName + "\"; filename=\"" + fileName + "\""),
                    fileBody);
        }
    }

    return builder.build();
}
 
Example #6
Source File: OkHttpUploadRequest.java    From meiShi with Apache License 2.0 6 votes vote down vote up
private void addParams(MultipartBuilder builder, Map<String, String> params)
{
    if (builder == null)
    {
        throw new IllegalArgumentException("builder can not be null .");
    }

    if (params != null && !params.isEmpty())
    {
        for (String key : params.keySet())
        {
            builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + key + "\""),
                    RequestBody.create(null, params.get(key)));

        }
    }
}
 
Example #7
Source File: GzipInterceptor.java    From logbook with MIT License 6 votes vote down vote up
@Override
public Response intercept(final Chain chain) throws IOException {
    final Response response = chain.proceed(chain.request());

    if (isContentEncodingGzip(response)) {
        final Headers headers = response.headers()
                .newBuilder()
                .removeAll("Content-Encoding")
                .removeAll("Content-Length")
                .build();

        return response.newBuilder()
                .headers(headers)
                .body(new RealResponseBody(
                        headers,
                        buffer(new GzipSource(requireNonNull(response.body(), "body").source()))))
                .build();
    }

    return response;
}
 
Example #8
Source File: HttpUtil.java    From httplite with Apache License 2.0 6 votes vote down vote up
public static Charset getChartset(RecordedRequest request){
    Headers headers = request.getHeaders();
    String value = headers.get("content-type");
    String[] array = value.split(";");
    Charset charset = null;
    try {
        if(array.length>1&&array[1].startsWith("charset=")){
            String charSetStr = array[1].split("=")[1];
            charset = Charset.forName(charSetStr);
        }
    } catch (Exception e) {
        System.out.println("ContentType:"+value);
        e.printStackTrace();
    }
    if(charset==null){
        charset = Charset.forName("utf-8");
    }
    return charset;
}
 
Example #9
Source File: OkHttpRequestor.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
private static Map<String, List<String>> fromOkHttpHeaders(Headers headers) {
    Map<String, List<String>> responseHeaders = new HashMap<String, List<String>>(headers.size());
    for (String name : headers.names()) {
        responseHeaders.put(name, headers.values(name));
    }
    return responseHeaders;
}
 
Example #10
Source File: Ok2Lite.java    From httplite with Apache License 2.0 5 votes vote down vote up
static Headers createHeader(Map<String, List<String>> headers){
    if(headers!=null&&!headers.isEmpty()){
        Headers.Builder hb = new Headers.Builder();
        for(String key:headers.keySet()){
            List<String> values = headers.get(key);
            for(String value:values){
                hb.add(key,value);
            }
        }
        return hb.build();
    }
    return null;
}
 
Example #11
Source File: ResponseTest.java    From octodroid with MIT License 5 votes vote down vote up
@Test
public void parseSuccessResponse() throws IOException, JSONException {
    Response<JSONObject> response = Response.parse(
            Headers.of("Name", "Value"),
            200,
            "{\"message\":\"This is a message\"}",
            new TypeToken<JSONObject>() {
            });
    assertThat(response.isSuccessful()).isTrue();
    assertThat(response.headers().get("Name")).isEqualTo("Value");
    assertThat(response.code()).isEqualTo(200);
    assertThat(response.body()).isEqualTo("{\"message\":\"This is a message\"}");
}
 
Example #12
Source File: ResponseTest.java    From octodroid with MIT License 5 votes vote down vote up
@Test
public void parseErrorResponse() throws IOException, JSONException {
    Response<JSONObject> response = Response.parse(
            Headers.of("Name", "Value"),
            422,
            "{\"message\":\"Validation Failed\",\"errors\":[{\"resource\":\"Issue\",\"field\":\"title\",\"code\":\"missing_field\"}]}",
            new TypeToken<JSONObject>() {
            });
    assertThat(response.isSuccessful()).isFalse();
    assertThat(response.headers().get("Name")).isEqualTo("Value");
    assertThat(response.code()).isEqualTo(422);
    assertThat(response.hasError()).isTrue();
    Error error = response.getError();
    assertThat(error.getMessage()).isEqualTo("Validation Failed");
}
 
Example #13
Source File: OkHttpLogInterceptor.java    From wasp with Apache License 2.0 5 votes vote down vote up
private static void logHeaders(Headers headers) {
  for (String headerName : headers.names()) {
    for (String headerValue : headers.values(headerName)) {
      Logger.d("Header - [" + headerName + ": " + headerValue + "]");
    }
  }
}
 
Example #14
Source File: SpotifyServiceAndroidTest.java    From spotify-web-api-android with MIT License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    Bundle arguments = InstrumentationRegistry.getArguments();
    String accessToken = arguments.getString("access_token");
    if (accessToken == null) {
        Assert.fail("Access token can't be null");
    }

    SpotifyApi spotifyApi = new SpotifyApi();
    spotifyApi.setAccessToken(accessToken);
    mService = spotifyApi.getService();

    mAuthHeader = Headers.of("Authorization", "Bearer " + accessToken);
}
 
Example #15
Source File: RestVolleyDownload.java    From RestVolley with Apache License 2.0 5 votes vote down vote up
private void notifyDownloadSuccess(final String url, final File file, final int httpCode, final Headers headers, final OnDownloadListener listener) {
    if (listener != null) {
        mMainHandler.post(new Runnable() {
            @Override
            public void run() {
                listener.onDownloadSuccess(url, file, httpCode, headers);
            }
        });
    }
}
 
Example #16
Source File: RestVolleyDownload.java    From RestVolley with Apache License 2.0 5 votes vote down vote up
private void notifyDownloadError(final String url, final Exception e, final int httpCode, final Headers headers, final OnDownloadListener listener) {
    if (listener != null) {
        mMainHandler.post(new Runnable() {
            @Override
            public void run() {
                listener.onDownloadFailure(url, e, httpCode, headers);
            }
        });
    }
}
 
Example #17
Source File: RestVolleyDownload.java    From RestVolley with Apache License 2.0 5 votes vote down vote up
private void notifyDownloadProgress(final String url, final long downloadBytes, final long totalBytes, final File localFile
        , final int httpCode, final Headers headers, final OnDownloadListener listener) {
    if (listener != null) {
        mMainHandler.post(new Runnable() {
            @Override
            public void run() {
                listener.onDownloadProgress(url, downloadBytes, totalBytes, localFile, httpCode, headers);
            }
        });
    }
}
 
Example #18
Source File: HttpURLConnectionImpl.java    From apiman with Apache License 2.0 5 votes vote down vote up
private Headers getHeaders() throws IOException {
  if (responseHeaders == null) {
    Response response = getResponse().getResponse();
    Headers headers = response.headers();

    responseHeaders = headers.newBuilder()
        .add(Platform.get().getPrefix() + "-Response-Source", responseSourceHeader(response))
        .build();
  }
  return responseHeaders;
}
 
Example #19
Source File: OkHttpRequest.java    From NewsMe with Apache License 2.0 5 votes vote down vote up
protected void appendHeaders()
{
    Headers.Builder headerBuilder = new Headers.Builder();
    if (headers == null || headers.isEmpty()) return;

    for (String key : headers.keySet())
    {
        headerBuilder.add(key, headers.get(key));
    }
    builder.headers(headerBuilder.build());
}
 
Example #20
Source File: PostFormRequest.java    From NewsMe with Apache License 2.0 5 votes vote down vote up
private void addParams(MultipartBuilder builder)
{
    if (params != null && !params.isEmpty())
    {
        for (String key : params.keySet())
        {
            builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + key + "\""),
                    RequestBody.create(null, params.get(key)));
        }
    }
}
 
Example #21
Source File: OkHttpStack.java    From styT with Apache License 2.0 5 votes vote down vote up
private URLHttpResponse responseFromConnection(Response okHttpResponse)
        throws IOException {
    URLHttpResponse response = new URLHttpResponse();
    //contentStream
    int responseCode = okHttpResponse.code();
    if (responseCode == -1) {
        throw new IOException(
                "Could not retrieve response code from HttpUrlConnection.");
    }
    response.setResponseCode(responseCode);
    response.setResponseMessage(okHttpResponse.message());

    response.setContentStream(okHttpResponse.body().byteStream());

    response.setContentLength(okHttpResponse.body().contentLength());
    response.setContentEncoding(okHttpResponse.header("Content-Encoding"));
    if (okHttpResponse.body().contentType() != null) {
        response.setContentType(okHttpResponse.body().contentType().type());
    }


    //header
    HashMap<String, String> headerMap = new HashMap<>();
    Headers responseHeaders = okHttpResponse.headers();
    for (int i = 0, len = responseHeaders.size(); i < len; i++) {
        final String name = responseHeaders.name(i), value = responseHeaders.value(i);
        if (name != null) {
            headerMap.put(name, value);
        }
    }
    response.setHeaders(headerMap);
    return response;
}
 
Example #22
Source File: HttpConnection.java    From tencentcloud-sdk-java with Apache License 2.0 5 votes vote down vote up
public Response getRequest(String url, Headers headers) throws TencentCloudSDKException {
  Request request = null;
  try {
    request = new Request.Builder().url(url).headers(headers).get().build();
  } catch (IllegalArgumentException e) {
    throw new TencentCloudSDKException(e.getClass().getName() + "-" + e.getMessage());
  }

  return this.doRequest(request);
}
 
Example #23
Source File: Ok2Lite.java    From httplite with Apache License 2.0 4 votes vote down vote up
private com.squareup.okhttp.Request makeRequest(Request request){
    com.squareup.okhttp.Request.Builder rb = new com.squareup.okhttp.Request.Builder().url(request.getUrl()).tag(request.getTag());
    Headers headers = createHeader(request.getHeaders());
    if(headers!=null) rb.headers(headers);
    alexclin.httplite.RequestBody liteBody = request.getRequestBody();
    RequestBody requestBody = null;
    if(liteBody!=null){
        requestBody = mFactory.convertBody(liteBody,request.getWrapListener());
    }
    switch (request.getMethod()){
        case GET:
            rb = rb.get();
            break;
        case POST:
            rb = rb.post(requestBody);
            break;
        case PUT:
            rb = rb.put(requestBody);
            break;
        case PATCH:
            rb = rb.patch(requestBody);
            break;
        case HEAD:
            rb = rb.head();
            break;
        case DELETE:
            if(requestBody==null){
                rb = rb.delete();
            }else{
                rb = rb.delete(requestBody);
            }
            break;
    }
    if(request.getCacheExpiredTime()>0){
        rb.cacheControl(new CacheControl.Builder().maxAge(request.getCacheExpiredTime(), TimeUnit.SECONDS).build());
    }else if(request.getCacheExpiredTime()== alexclin.httplite.Request.FORCE_CACHE){
        rb.cacheControl(CacheControl.FORCE_CACHE);
    }else if(request.getCacheExpiredTime()== alexclin.httplite.Request.NO_CACHE){
        rb.cacheControl(CacheControl.FORCE_NETWORK);
    }
    return rb.build();
}
 
Example #24
Source File: Response.java    From octodroid with MIT License 4 votes vote down vote up
public Headers headers() {
    return headers;
}
 
Example #25
Source File: HttpURLConnectionImpl.java    From apiman with Apache License 2.0 4 votes vote down vote up
private HttpEngine newHttpEngine(String method, Connection connection,
    RetryableSink requestBody, Response priorResponse) {
  // OkHttp's Call API requires a placeholder body; the real body will be streamed separately.
  RequestBody placeholderBody = HttpMethod.requiresRequestBody(method)
      ? EMPTY_REQUEST_BODY
      : null;
  Request.Builder builder = new Request.Builder()
      .url(getURL())
      .method(method, placeholderBody);
  Headers headers = requestHeaders.build();
  for (int i = 0, size = headers.size(); i < size; i++) {
    builder.addHeader(headers.name(i), headers.value(i));
  }

  boolean bufferRequestBody = false;
  if (HttpMethod.permitsRequestBody(method)) {
    // Specify how the request body is terminated.
    if (fixedContentLength != -1) {
      builder.header("Content-Length", Long.toString(fixedContentLength));
    } else if (chunkLength > 0) {
      builder.header("Transfer-Encoding", "chunked");
    } else {
      bufferRequestBody = true;
    }

    // Add a content type for the request body, if one isn't already present.
    if (headers.get("Content-Type") == null) {
      builder.header("Content-Type", "application/x-www-form-urlencoded");
    }
  }

  if (headers.get("User-Agent") == null) {
    builder.header("User-Agent", defaultUserAgent());
  }

  Request request = builder.build();

  // If we're currently not using caches, make sure the engine's client doesn't have one.
  OkHttpClient engineClient = client;
  if (Internal.instance.internalCache(engineClient) != null && !getUseCaches()) {
    engineClient = client.clone().setCache(null);
  }

  return new HttpEngine(engineClient, request, bufferRequestBody, true, false, connection, null,
      requestBody, priorResponse);
}
 
Example #26
Source File: HttpUtil.java    From httplite with Apache License 2.0 4 votes vote down vote up
public static String getMimeType(RecordedRequest request){
    Headers headers = request.getHeaders();
    String value = headers.get("content-type");
    String[] array = value.split(";");
    return array[0];
}
 
Example #27
Source File: ApiKeyAuth.java    From huaweicloud-cs-sdk with Apache License 2.0 4 votes vote down vote up
public Request applyToParams(Request request) {
    if (serviceName == null || region == null || accessKey == null || secretKey == null) {
        return request;
    }
    DefaultRequest reqForSigner = new DefaultRequest(this.serviceName);
    try {
        reqForSigner.setEndpoint(request.uri());

        reqForSigner.setHttpMethod(HttpMethodName.valueOf(request.method()));

        if(!projectId.isEmpty()) {
            reqForSigner.addHeader("X-Project-Id", projectId);
        }

        // add query string
        String urlString = request.urlString();
        if (urlString.contains("?")) {
            String parameters = urlString.substring(urlString.indexOf("?") + 1);
            Map<String, String> parametersMap = new HashMap<>();

            if (!parameters.isEmpty()) {
                for (String p : parameters.split("&")) {

                    String key = p.split("=")[0];
                    String value = p.split("=")[1];
                    parametersMap.put(key, value);
                }
                reqForSigner.setParameters(parametersMap);
            }
        }

        // add body
        if (request.body() != null) {
            Request copy = request.newBuilder().build();
            Buffer buffer = new Buffer();
            copy.body().writeTo(buffer);
            reqForSigner.setContent(new ByteArrayInputStream(buffer.readByteArray()));
        }

        Signer signer = SignerFactory.getSigner(serviceName, region);
        signer.sign(reqForSigner, new BasicCredentials(this.accessKey, this.secretKey));

        Request.Builder builder = request.newBuilder();
        builder.headers(Headers.of(reqForSigner.getHeaders()));
        return builder.build();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return request;
}
 
Example #28
Source File: RestVolleyDownload.java    From RestVolley with Apache License 2.0 4 votes vote down vote up
/**
 * add header.
 * @param headers {@link Headers}
 * @return {@link RestVolleyDownload}
 */
public RestVolleyDownload addHeader(Headers headers) {
    mRequestBuilder.headers(headers);

    return this;
}
 
Example #29
Source File: ApiKeyAuth.java    From huaweicloud-cs-sdk with Apache License 2.0 4 votes vote down vote up
public Request applyToParams(Request request) {
    if (serviceName == null || region == null || accessKey == null || secretKey == null) {
        return request;
    }
    DefaultRequest reqForSigner = new DefaultRequest(this.serviceName);
    try {
        reqForSigner.setEndpoint(request.uri());

        reqForSigner.setHttpMethod(HttpMethodName.valueOf(request.method()));

        if(!projectId.isEmpty()) {
            reqForSigner.addHeader("X-Project-Id", projectId);
        }

        // add query string
        String urlString = request.urlString();
        if (urlString.contains("?")) {
            String parameters = urlString.substring(urlString.indexOf("?") + 1);
            Map<String, String> parametersMap = new HashMap<>();

            if (!parameters.isEmpty()) {
                for (String p : parameters.split("&")) {

                    String key = p.split("=")[0];
                    String value = p.split("=")[1];
                    parametersMap.put(key, value);
                }
                reqForSigner.setParameters(parametersMap);
            }
        }

        // add body
        if (request.body() != null) {
            Request copy = request.newBuilder().build();
            Buffer buffer = new Buffer();
            copy.body().writeTo(buffer);
            reqForSigner.setContent(new ByteArrayInputStream(buffer.readByteArray()));
        }

        Signer signer = SignerFactory.getSigner(serviceName, region);
        signer.sign(reqForSigner, new BasicCredentials(this.accessKey, this.secretKey));

        Request.Builder builder = request.newBuilder();
        builder.headers(Headers.of(reqForSigner.getHeaders()));
        return builder.build();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return request;
}
 
Example #30
Source File: RestVolleyDownload.java    From RestVolley with Apache License 2.0 3 votes vote down vote up
/**
 * constructor.
 * @param downloadFile download file
 * @param headers {@link Headers}
 * @param httpCode response http code
 * @param message response message
 */
public DownloadResponse(File downloadFile, Headers headers, int httpCode, String message) {
    this.downloadFile = downloadFile;
    this.headers = headers;
    this.httpCode = httpCode;
    this.message = message;
}