Java 类com.squareup.okhttp.Headers 实例源码

项目:boohee_v5.6    文件:OkHeaders.java   
public static Map<String, List<String>> toMultimap(Headers headers, String valueForNullKey) {
    Map<String, List<String>> result = new TreeMap(FIELD_NAME_COMPARATOR);
    int size = headers.size();
    for (int i = 0; i < size; i++) {
        String fieldName = headers.name(i);
        String value = headers.value(i);
        List<String> allValues = new ArrayList();
        List<String> otherValues = (List) result.get(fieldName);
        if (otherValues != null) {
            allValues.addAll(otherValues);
        }
        allValues.add(value);
        result.put(fieldName, Collections.unmodifiableList(allValues));
    }
    if (valueForNullKey != null) {
        result.put(null, Collections.unmodifiableList(Collections.singletonList
                (valueForNullKey)));
    }
    return Collections.unmodifiableMap(result);
}
项目:ktball    文件:OkHttpRequest.java   
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());
}
项目:boohee_v5.6    文件:HttpEngine.java   
private static Headers combine(Headers cachedHeaders, Headers networkHeaders) throws
        IOException {
    int i;
    Headers.Builder result = new Headers.Builder();
    int size = cachedHeaders.size();
    for (i = 0; i < size; i++) {
        String fieldName = cachedHeaders.name(i);
        String value = cachedHeaders.value(i);
        if (!("Warning".equalsIgnoreCase(fieldName) && value.startsWith("1")) && (!OkHeaders
                .isEndToEnd(fieldName) || networkHeaders.get(fieldName) == null)) {
            result.add(fieldName, value);
        }
    }
    size = networkHeaders.size();
    for (i = 0; i < size; i++) {
        fieldName = networkHeaders.name(i);
        if (!"Content-Length".equalsIgnoreCase(fieldName) && OkHeaders.isEndToEnd(fieldName)) {
            result.add(fieldName, networkHeaders.value(i));
        }
    }
    return result.build();
}
项目:ktball    文件:OkHttpUploadRequest.java   
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)));

        }
    }
}
项目:ktball    文件:OkHttpUploadRequest.java   
@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();
}
项目:meishiDemo    文件:OkHttpUploadRequest.java   
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)));

        }
    }
}
项目:meishiDemo    文件:OkHttpUploadRequest.java   
@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();
}
项目:meishiDemo    文件:OkHttpRequest.java   
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());
}
项目:httplite    文件:HttpUtil.java   
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;
}
项目:Mobile-Office    文件:RequestFactory.java   
private static Request buildUpload(ACTION action, File[] files,
        String[] filenames, Object requestBean) {
    String json = GsonTool.toJson(requestBean);
    MultipartBuilder builder = new MultipartBuilder()
            .type(MultipartBuilder.FORM);
    if (files != null) {
        for (int i = 0; i < filenames.length; i++) {
            builder.addPart(Headers.of("Content-Disposition",
                    "form-data;name=\"" + "file" + i + "\";filename=\""
                            + filenames[i] + "\""), RequestBody.create(
                    MediaType.parse("application/octet-stream"), files[i]));
        }
    }
    builder.addPart(
            Headers.of("Content-Disposition", "form-data; name=\""
                    + RequestArr.requestArg + "\""),
            RequestBody.create(null, json));
    String url = RequestArr.mainUrl + RequestArr.mUrls.get(action);
    return new Request.Builder().url(url).post(builder.build()).build();
}
项目:FMTech    文件:OkHeaders.java   
public static Map<String, List<String>> toMultimap$29224fb9(Headers paramHeaders)
{
  TreeMap localTreeMap = new TreeMap(FIELD_NAME_COMPARATOR);
  int i = 0;
  int j = paramHeaders.namesAndValues.length / 2;
  while (i < j)
  {
    String str1 = paramHeaders.name(i);
    String str2 = paramHeaders.value(i);
    ArrayList localArrayList = new ArrayList();
    List localList = (List)localTreeMap.get(str1);
    if (localList != null) {
      localArrayList.addAll(localList);
    }
    localArrayList.add(str2);
    localTreeMap.put(str1, Collections.unmodifiableList(localArrayList));
    i++;
  }
  return Collections.unmodifiableMap(localTreeMap);
}
项目:FMTech    文件:HttpConnection.java   
public final Response.Builder readResponse()
  throws IOException
{
  if ((this.state != 1) && (this.state != 3)) {
    throw new IllegalStateException("state: " + this.state);
  }
  StatusLine localStatusLine;
  Response.Builder localBuilder;
  do
  {
    localStatusLine = StatusLine.parse(this.source.readUtf8LineStrict());
    localBuilder = new Response.Builder();
    localBuilder.protocol = localStatusLine.protocol;
    localBuilder.code = localStatusLine.code;
    localBuilder.message = localStatusLine.message;
    Headers.Builder localBuilder1 = new Headers.Builder();
    readHeaders(localBuilder1);
    localBuilder1.add(OkHeaders.SELECTED_PROTOCOL, localStatusLine.protocol.toString());
    localBuilder.headers(localBuilder1.build());
  } while (localStatusLine.code == 100);
  this.state = 4;
  return localBuilder;
}
项目:FMTech    文件:HttpConnection.java   
public final void writeRequest(Headers paramHeaders, String paramString)
  throws IOException
{
  if (this.state != 0) {
    throw new IllegalStateException("state: " + this.state);
  }
  this.sink.writeUtf8(paramString).writeUtf8("\r\n");
  int i = 0;
  int j = paramHeaders.namesAndValues.length / 2;
  while (i < j)
  {
    this.sink.writeUtf8(paramHeaders.name(i)).writeUtf8(": ").writeUtf8(paramHeaders.value(i)).writeUtf8("\r\n");
    i++;
  }
  this.sink.writeUtf8("\r\n");
  this.state = 1;
}
项目:FMTech    文件:CurlLoggingInterceptor.java   
private static boolean isBinaryContent(Headers paramHeaders, MediaType paramMediaType)
{
  List localList = paramHeaders.values("Content-Encoding");
  if (localList != null)
  {
    Iterator localIterator = localList.iterator();
    while (localIterator.hasNext()) {
      if (((String)localIterator.next()).equalsIgnoreCase("gzip")) {
        return true;
      }
    }
  }
  String str1 = paramMediaType.type;
  String str2 = paramMediaType.subtype;
  if (str1 != null)
  {
    if (str1.equals("text")) {
      return false;
    }
    if ((str1.equals("application")) && (str2 != null)) {
      return (!str2.equals("xml")) && (!str2.equals("json"));
    }
  }
  return true;
}
项目:KwPresent    文件:DownLoadManager.java   
private Request buildMultipartFormRequest(String url, String[] fileKeys, File[] files, Param[] paramses) {
    paramses = validateParam(paramses);
    MultipartBuilder builder = new MultipartBuilder().type(MultipartBuilder.FORM);

    for (Param param : paramses) {
        builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + param.key + "\""), RequestBody.create(null, param.value));
    }

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

    RequestBody requestBody = builder.build();
    return new Request.Builder().url(url).post(requestBody).build();
}
项目:android-kit-old    文件:OkHttpUploadRequest.java   
@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();
}
项目:OkHttpTutorial    文件:OkHttpUtil.java   
private RequestBody buildMultipartFormRequest(String[] fileKeys, File[] files, Map<String, String> params) {
    MultipartBuilder builder = new MultipartBuilder().type(MultipartBuilder.FORM);
    for (Map.Entry<String, String> entry : params.entrySet()) {
        builder.addPart(Headers.of("Content-Disposition", "form-data;name=\"" + entry.getKey() + "\""), RequestBody.create(null, entry.getValue()));
    }
    if (files != null && fileKeys != null && files.length == fileKeys.length) {
        RequestBody fileBody = null;
        for (int i = 0; i < files.length; i++) {
            fileBody = RequestBody.create(MediaType.parse(getMimeType(files[i].getName())), files[i]);
            builder.addPart(Headers.of("Content-Disposition",
                    "form-data;name=\"" + fileKeys[i] + "\";filename=\"" + files[i].getName() + "\""), fileBody);
        }
    } else {
        try {
            throw new Exception("文件名参数长度和文件实体内容长度不一致");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return builder.build();
}
项目:meiShi    文件:OkHttpUploadRequest.java   
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)));

        }
    }
}
项目:meiShi    文件:OkHttpUploadRequest.java   
@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();
}
项目:meiShi    文件:OkHttpRequest.java   
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());
}
项目:birudo    文件:BaseHttpClient.java   
private void addHeader() {
    try {
        URI uri = new URI(url);
        String userInfo = uri.getUserInfo();
        if (userInfo != null) {
            setHeader("Authorization", "Basic " + base64Encode(userInfo));
        }
    } catch (URISyntaxException e) {
        debug(e);
    }

    StringBuilder userAgent = new StringBuilder("BirudoRogu-Android");
    setHeader("User-Agent", userAgent.toString());
    // set headers on request
    Headers.Builder headerBuilder = new Headers.Builder();
    for (String key : header.keySet()) {
        headerBuilder.set(key, header.get(key));
    }
    setHeaders(headerBuilder.build());
}
项目:okhttp-utils    文件:OkHttpUploadRequest.java   
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)));

        }
    }
}
项目:okhttp-utils    文件:OkHttpUploadRequest.java   
@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();
}
项目:okhttp-utils    文件:OkHttpRequest.java   
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());
}
项目:octodroid    文件:PaginationHeaderParser.java   
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);
}
项目:spdymcsclient    文件:UTILS.java   
public static HttpResponse transformResponse(Response response) {
    int code = response.code();
    String message = response.message();
    BasicHttpResponse httpResponse = new BasicHttpResponse(HTTP_1_1, code, message);

    ResponseBody body = response.body();
    InputStreamEntity entity = new InputStreamEntity(body.byteStream(), body.contentLength());
    httpResponse.setEntity(entity);

    Headers headers = response.headers();
    for (int i = 0; i < headers.size(); i++) {
        String name = headers.name(i);
        String value = headers.value(i);
        httpResponse.addHeader(name, value);
        if ("Content-Type".equalsIgnoreCase(name)) {
            entity.setContentType(value);
        } else if ("Content-Encoding".equalsIgnoreCase(name)) {
            entity.setContentEncoding(value);
        }
    }

    return httpResponse;
}
项目:spdymcsclient    文件:OkApacheClient.java   
private static HttpResponse transformResponse(Response response) {
  int code = response.code();
  String message = response.message();
  BasicHttpResponse httpResponse = new BasicHttpResponse(HTTP_1_1, code, message);

  ResponseBody body = response.body();
  InputStreamEntity entity = new InputStreamEntity(body.byteStream(), body.contentLength());
  httpResponse.setEntity(entity);

  Headers headers = response.headers();
  for (int i = 0; i < headers.size(); i++) {
    String name = headers.name(i);
    String value = headers.value(i);
    httpResponse.addHeader(name, value);
    if ("Content-Type".equalsIgnoreCase(name)) {
      entity.setContentType(value);
    } else if ("Content-Encoding".equalsIgnoreCase(name)) {
      entity.setContentEncoding(value);
    }
  }

  return httpResponse;
}
项目:spdymcsclient    文件:OkHeaders.java   
/**
 * Returns an immutable map containing each field to its list of values.
 *
 * @param valueForNullKey the request line for requests, or the status line
 *     for responses. If non-null, this value is mapped to the null key.
 */
public static Map<String, List<String>> toMultimap(Headers headers, String valueForNullKey) {
  Map<String, List<String>> result = new TreeMap<>(FIELD_NAME_COMPARATOR);
  for (int i = 0; i < headers.size(); i++) {
    String fieldName = headers.name(i);
    String value = headers.value(i);

    List<String> allValues = new ArrayList<>();
    List<String> otherValues = result.get(fieldName);
    if (otherValues != null) {
      allValues.addAll(otherValues);
    }
    allValues.add(value);
    result.put(fieldName, Collections.unmodifiableList(allValues));
  }
  if (valueForNullKey != null) {
    result.put(null, Collections.unmodifiableList(Collections.singletonList(valueForNullKey)));
  }
  return Collections.unmodifiableMap(result);
}
项目:spdymcsclient    文件:OkHeaders.java   
private static Set<String> varyFields(Response response) {
  Set<String> result = Collections.emptySet();
  Headers headers = response.headers();
  for (int i = 0; i < headers.size(); i++) {
    if (!"Vary".equalsIgnoreCase(headers.name(i))) continue;

    String value = headers.value(i);
    if (result.isEmpty()) {
      result = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
    }
    for (String varyField : value.split(",")) {
      result.add(varyField.trim());
    }
  }
  return result;
}
项目:spdymcsclient    文件:OkHeaders.java   
/**
 * Returns the subset of the headers in {@code response}'s request that
 * impact the content of response's body.
 */
public static Headers varyHeaders(Response response) {
  Set<String> varyFields = varyFields(response);
  if (varyFields.isEmpty()) return new Headers.Builder().build();

  // Use the request headers sent over the network, since that's what the
  // response varies on. Otherwise OkHttp-supplied headers like
  // "Accept-Encoding: gzip" may be lost.
  Headers requestHeaders = response.networkResponse().request().headers();

  Headers.Builder result = new Headers.Builder();
  for (int i = 0; i < requestHeaders.size(); i++) {
    String fieldName = requestHeaders.name(i);
    if (varyFields.contains(fieldName)) {
      result.add(fieldName, requestHeaders.value(i));
    }
  }
  return result.build();
}
项目:spdymcsclient    文件:HttpConnection.java   
/** Parses bytes of a response header from an HTTP transport. */
public Response.Builder readResponse() throws IOException {
  if (state != STATE_OPEN_REQUEST_BODY && state != STATE_READ_RESPONSE_HEADERS) {
    throw new IllegalStateException("state: " + state);
  }

  while (true) {
    StatusLine statusLine = StatusLine.parse(source.readUtf8LineStrict());

    Response.Builder responseBuilder = new Response.Builder()
        .protocol(statusLine.protocol)
        .code(statusLine.code)
        .message(statusLine.message);

    Headers.Builder headersBuilder = new Headers.Builder();
    readHeaders(headersBuilder);
    headersBuilder.add(OkHeaders.SELECTED_PROTOCOL, statusLine.protocol.toString());
    responseBuilder.headers(headersBuilder.build());

    if (statusLine.code != HTTP_CONTINUE) {
      state = STATE_OPEN_RESPONSE_BODY;
      return responseBuilder;
    }
  }
}
项目:spdymcsclient    文件:HttpConnection.java   
private void readChunkSize() throws IOException {
  // read the suffix of the previous chunk
  if (bytesRemainingInChunk != NO_CHUNK_YET) {
    source.readUtf8LineStrict();
  }
  String chunkSizeString = source.readUtf8LineStrict();
  int index = chunkSizeString.indexOf(";");
  if (index != -1) {
    chunkSizeString = chunkSizeString.substring(0, index);
  }
  try {
    bytesRemainingInChunk = Integer.parseInt(chunkSizeString.trim(), 16);
  } catch (NumberFormatException e) {
    throw new ProtocolException("Expected a hex chunk size but was " + chunkSizeString);
  }
  if (bytesRemainingInChunk == 0) {
    hasMoreChunks = false;
    Headers.Builder trailersBuilder = new Headers.Builder();
    readHeaders(trailersBuilder);
    httpEngine.receiveHeaders(trailersBuilder.build());
    endOfInput(true);
  }
}
项目:spdymcsclient    文件:JavaApiConverter.java   
/**
 * Extracts OkHttp headers from the supplied {@link Map}. Only real headers are
 * extracted. Any entry (one with a {@code null} key) is discarded.
 */
// @VisibleForTesting
static Headers extractOkHeaders(Map<String, List<String>> javaHeaders) {
  Headers.Builder okHeadersBuilder = new Headers.Builder();
  for (Map.Entry<String, List<String>> javaHeader : javaHeaders.entrySet()) {
    String name = javaHeader.getKey();
    if (name == null) {
      // The Java API uses the null key to store the status line in responses.
      // Earlier versions of OkHttp would use the null key to store the "request line" in
      // requests. e.g. "GET / HTTP 1.1". Although this is no longer the case it must be
      // explicitly ignored because Headers.Builder does not support null keys.
      continue;
    }
    for (String value : javaHeader.getValue()) {
      okHeadersBuilder.add(name, value);
    }
  }
  return okHeadersBuilder.build();
}
项目:spdymcsclient    文件:JavaApiConverter.java   
/**
 * Creates an OkHttp Response.Body containing the supplied information.
 */
private static ResponseBody createOkBody(final Headers okHeaders, InputStream body) {
  final BufferedSource source = Okio.buffer(Okio.source(body));
  return new ResponseBody() {
    @Override public MediaType contentType() {
      String contentTypeHeader = okHeaders.get("Content-Type");
      return contentTypeHeader == null ? null : MediaType.parse(contentTypeHeader);
    }
    @Override public long contentLength() {
      return OkHeaders.contentLength(okHeaders);
    }
    @Override public BufferedSource source() {
      return source;
    }
  };
}
项目:platform_external_okhttp    文件:OkHeaders.java   
/**
 * Returns an immutable map containing each field to its list of values.
 *
 * @param valueForNullKey the request line for requests, or the status line
 *     for responses. If non-null, this value is mapped to the null key.
 */
public static Map<String, List<String>> toMultimap(Headers headers, String valueForNullKey) {
  Map<String, List<String>> result = new TreeMap<String, List<String>>(FIELD_NAME_COMPARATOR);
  for (int i = 0; i < headers.size(); i++) {
    String fieldName = headers.name(i);
    String value = headers.value(i);

    List<String> allValues = new ArrayList<String>();
    List<String> otherValues = result.get(fieldName);
    if (otherValues != null) {
      allValues.addAll(otherValues);
    }
    allValues.add(value);
    result.put(fieldName, Collections.unmodifiableList(allValues));
  }
  if (valueForNullKey != null) {
    result.put(null, Collections.unmodifiableList(Collections.singletonList(valueForNullKey)));
  }
  return Collections.unmodifiableMap(result);
}
项目:platform_external_okhttp    文件:HttpConnection.java   
/** Parses bytes of a response header from an HTTP transport. */
public Response.Builder readResponse() throws IOException {
  if (state != STATE_OPEN_REQUEST_BODY && state != STATE_READ_RESPONSE_HEADERS) {
    throw new IllegalStateException("state: " + state);
  }

  while (true) {
    String statusLineString = source.readUtf8LineStrict();
    StatusLine statusLine = new StatusLine(statusLineString);

    Response.Builder responseBuilder = new Response.Builder()
        .statusLine(statusLine)
        .header(OkHeaders.SELECTED_PROTOCOL, Protocol.HTTP_11.name.utf8());

    Headers.Builder headersBuilder = new Headers.Builder();
    readHeaders(headersBuilder);
    responseBuilder.headers(headersBuilder.build());

    if (statusLine.code() != HTTP_CONTINUE) {
      state = STATE_OPEN_RESPONSE_BODY;
      return responseBuilder;
    }
  }
}
项目:platform_external_okhttp    文件:HttpConnection.java   
private void readChunkSize() throws IOException {
  // read the suffix of the previous chunk
  if (bytesRemainingInChunk != NO_CHUNK_YET) {
    source.readUtf8LineStrict();
  }
  String chunkSizeString = source.readUtf8LineStrict();
  int index = chunkSizeString.indexOf(";");
  if (index != -1) {
    chunkSizeString = chunkSizeString.substring(0, index);
  }
  try {
    bytesRemainingInChunk = Integer.parseInt(chunkSizeString.trim(), 16);
  } catch (NumberFormatException e) {
    throw new ProtocolException("Expected a hex chunk size but was " + chunkSizeString);
  }
  if (bytesRemainingInChunk == 0) {
    hasMoreChunks = false;
    Headers.Builder trailersBuilder = new Headers.Builder();
    readHeaders(trailersBuilder);
    httpEngine.receiveHeaders(trailersBuilder.build());
    endOfInput(true);
  }
}
项目:platform_external_okhttp    文件:JavaApiConverter.java   
/**
 * Extracts OkHttp headers from the supplied {@link Map}. Only real headers are
 * extracted. Any entry (one with a {@code null} key) is discarded.
 */
// @VisibleForTesting
static Headers extractOkHeaders(Map<String, List<String>> javaHeaders) {
  Headers.Builder okHeadersBuilder = new Headers.Builder();
  for (Map.Entry<String, List<String>> javaHeader : javaHeaders.entrySet()) {
    String name = javaHeader.getKey();
    if (name == null) {
      // The Java API uses the null key to store the status line in responses.
      // Earlier versions of OkHttp would use the null key to store the "request line" in
      // requests. e.g. "GET / HTTP 1.1". Although this is no longer the case it must be
      // explicitly ignored because Headers.Builder does not support null keys.
      continue;
    }
    for (String value : javaHeader.getValue()) {
      okHeadersBuilder.add(name, value);
    }
  }
  return okHeadersBuilder.build();
}
项目:platform_external_okhttp    文件:JavaApiConverter.java   
/**
 * Creates an OkHttp Response.Body containing the supplied information.
 */
private static Response.Body createOkBody(final Headers okHeaders, final InputStream body) {
  return new Response.Body() {

    @Override
    public boolean ready() throws IOException {
      return true;
    }

    @Override
    public MediaType contentType() {
      String contentTypeHeader = okHeaders.get("Content-Type");
      return contentTypeHeader == null ? null : MediaType.parse(contentTypeHeader);
    }

    @Override
    public long contentLength() {
      return OkHeaders.contentLength(okHeaders);
    }

    @Override
    public InputStream byteStream() {
      return body;
    }
  };
}
项目:platform_external_okhttp    文件:HeadersTest.java   
@Test public void parseNameValueBlock() throws IOException {
  List<Header> headerBlock = headerEntries(
      "cache-control", "no-cache, no-store",
      "set-cookie", "Cookie1\u0000Cookie2",
      ":status", "200 OK",
      ":version", "HTTP/1.1");
  Request request = new Request.Builder().url("http://square.com/").build();
  Response response =
      SpdyTransport.readNameValueBlock(headerBlock, Protocol.SPDY_3).request(request).build();
  Headers headers = response.headers();
  assertEquals(4, headers.size());
  assertEquals("HTTP/1.1 200 OK", response.statusLine());
  assertEquals("no-cache, no-store", headers.get("cache-control"));
  assertEquals("Cookie2", headers.get("set-cookie"));
  assertEquals(Protocol.SPDY_3.name.utf8(), headers.get(OkHeaders.SELECTED_PROTOCOL));
  assertEquals(OkHeaders.SELECTED_PROTOCOL, headers.name(0));
  assertEquals(Protocol.SPDY_3.name.utf8(), headers.value(0));
  assertEquals("cache-control", headers.name(1));
  assertEquals("no-cache, no-store", headers.value(1));
  assertEquals("set-cookie", headers.name(2));
  assertEquals("Cookie1", headers.value(2));
  assertEquals("set-cookie", headers.name(3));
  assertEquals("Cookie2", headers.value(3));
  assertNull(headers.get(":status"));
  assertNull(headers.get(":version"));
}