Exemplo n.º 1
0
  @Override
  public Response intercept(Chain chain) throws IOException {
    String requestId = String.valueOf(mNextRequestId.getAndIncrement());

    Request request = chain.request();

    int requestSize = 0;
    if (mEventReporter.isEnabled()) {
      OkHttpInspectorRequest inspectorRequest = new OkHttpInspectorRequest(requestId, request);
      mEventReporter.requestWillBeSent(inspectorRequest);
      byte[] requestBody = inspectorRequest.body();
      if (requestBody != null) {
        requestSize += requestBody.length;
      }
    }

    Response response;
    try {
      response = chain.proceed(request);
    } catch (IOException e) {
      if (mEventReporter.isEnabled()) {
        mEventReporter.httpExchangeFailed(requestId, e.toString());
      }
      throw e;
    }

    if (mEventReporter.isEnabled()) {
      if (requestSize > 0) {
        mEventReporter.dataSent(requestId, requestSize, requestSize);
      }

      Connection connection = chain.connection();
      mEventReporter.responseHeadersReceived(
          new OkHttpInspectorResponse(requestId, request, response, connection));

      ResponseBody body = response.body();
      MediaType contentType = null;
      InputStream responseStream = null;
      if (body != null) {
        contentType = body.contentType();
        responseStream = body.byteStream();
      }

      responseStream =
          mEventReporter.interpretResponseStream(
              requestId,
              contentType != null ? contentType.toString() : null,
              response.header("Content-Encoding"),
              responseStream,
              new DefaultResponseHandler(mEventReporter, requestId));
      if (responseStream != null) {
        response =
            response.newBuilder().body(new ForwardingResponseBody(body, responseStream)).build();
      }
    }

    return response;
  }
Exemplo n.º 2
0
 HttpEntityBody(HttpEntity httpentity, String s) {
   entity = httpentity;
   if (s != null) {
     mediaType = MediaType.parse(s);
     return;
   }
   if (httpentity.getContentType() != null) {
     mediaType = MediaType.parse(httpentity.getContentType().getValue());
     return;
   } else {
     mediaType = DEFAULT_MEDIA_TYPE;
     return;
   }
 }
  @Override
  public void post(
      String url,
      RequestParams params,
      Net.Parser<T> parser,
      Net.Callback<T> callback,
      Object tag) {
    MultipartBuilder builder = new MultipartBuilder().type(MultipartBuilder.FORM);
    // 添加普通的参数
    LinkedHashMap<String, String> map = params.get();
    for (Iterator<String> iterator = map.keySet().iterator(); iterator.hasNext(); ) {
      String key = iterator.next();
      builder.addPart(
          Headers.of("Content-Disposition", "form-data; name=\"" + key + "\""),
          RequestBody.create(null, map.get(key)));
    }
    // 添加文件参数
    LinkedHashMap<String, File> files = params.files();
    for (Iterator<String> iterator = files.keySet().iterator(); iterator.hasNext(); ) {
      String key = iterator.next();
      File file = files.get(key);
      builder.addPart(
          Headers.of(
              "Content-Disposition",
              "form-data; name=\"" + key + "\";filename=\"" + file.getName() + "\""),
          RequestBody.create(MediaType.parse("application/octet-stream"), file));
    }

    // 组装Request
    Request request = new Request.Builder().url(url).post(builder.build()).build();
    call(request, parser, callback, tag);
  }
Exemplo n.º 4
0
    private Request buildMultipartFormRequest(
        String url, File[] files, String[] fileKeys, Param[] params) {
      params = validateParam(params);

      MultipartBuilder builder = new MultipartBuilder().type(MultipartBuilder.FORM);

      for (Param param : params) {
        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(guessMimeType(fileName)), file);
          // TODO 根据文件名设置contentType
          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();
    }
Exemplo n.º 5
0
  public static void main(String[] args) throws IOException {
    OkHttpClient client = new OkHttpClient();
    final MediaType MEDIA_TYPE_TEXT = MediaType.parse("text/plain");
    final String postBody = "Hello World";

    RequestBody requestBody =
        new RequestBody() {
          @Override
          public MediaType contentType() {
            return MEDIA_TYPE_TEXT;
          }

          @Override
          public void writeTo(BufferedSink sink) throws IOException {
            sink.writeUtf8(postBody);
          }

          @Override
          public long contentLength() throws IOException {
            return postBody.length();
          }
        };

    Request request = new Request.Builder().url("http://www.baidu.com").post(requestBody).build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) {
      throw new IOException("服务器端错误: " + response);
    }

    System.out.println(response.body().string());
  }
Exemplo n.º 6
0
    private String sendPop(Transaction tx) {
      RequestBody requestBody =
          RequestBody.create(MediaType.parse("application/bitcoin-pop"), tx.toBytes());

      URL url;
      try {
        url = new URL(popRequest.getP());
        if (!"http".equals(url.getProtocol()) && !"https".equals(url.getProtocol())) {
          return "Invalid Url, expected protocol http or https: " + popRequest.getP();
        }
      } catch (MalformedURLException e) {
        return "Invalid Url: " + popRequest.getP();
      }

      Request request = new Request.Builder().url(url).post(requestBody).build();

      OkHttpClient httpClient = new OkHttpClient();
      if (_mbwManager.getTorMode() == ServerEndpointType.Types.ONLY_TOR
          && _mbwManager.getTorManager() != null) {
        httpClient = _mbwManager.getTorManager().setupClient(httpClient);
      }

      try {
        Response response = httpClient.newCall(request).execute();
        if (response.isSuccessful()) {
          return response.body().string();
        } else {
          return "Error occurred: " + response.code();
        }
      } catch (IOException e) {
        return "Cannot communicate with server: " + e.getMessage();
      }
    }
Exemplo n.º 7
0
  public static void sendMobileNumberToServer(Context context, String user_cell_number) {
    OkHttpClient okhttp = new OkHttpClient();
    String json =
        String.format(
            "{\"user_id\" : \"%s\",\"user_mobile_number\" : \"%s\"}",
            com.example.muditi.deligoo.Omoyo.shared.getString("user_id", "1007"), user_cell_number);
    final MediaType JSON = MediaType.parse("application/json;charset=utf-8");
    RequestBody requestbody = RequestBody.create(JSON, json);
    Request request =
        new Request.Builder()
            .url(
                "http://"
                    + context.getResources().getString(R.string.ip)
                    + "/userMobileNumberDataEntry/")
            .post(requestbody)
            .build();
    Call call = okhttp.newCall(request);
    call.enqueue(
        new Callback() {
          @Override
          public void onFailure(Request request, IOException e) {}

          @Override
          public void onResponse(Response response) throws IOException {
            if (response.isSuccessful()) {
              String data = response.body().string();
              com.example.muditi.deligoo.Omoyo.edit.putBoolean(
                  "user_mobile_number_sended_to_server_successfully", true);
              com.example.muditi.deligoo.Omoyo.edit.commit();
            }
          }
        });
  }
Exemplo n.º 8
0
final class HttpEntityBody extends RequestBody {

  private static final MediaType DEFAULT_MEDIA_TYPE = MediaType.parse("application/octet-stream");
  private final HttpEntity entity;
  private final MediaType mediaType;

  HttpEntityBody(HttpEntity httpentity, String s) {
    entity = httpentity;
    if (s != null) {
      mediaType = MediaType.parse(s);
      return;
    }
    if (httpentity.getContentType() != null) {
      mediaType = MediaType.parse(httpentity.getContentType().getValue());
      return;
    } else {
      mediaType = DEFAULT_MEDIA_TYPE;
      return;
    }
  }

  public long contentLength() {
    return entity.getContentLength();
  }

  public MediaType contentType() {
    return mediaType;
  }

  public void writeTo(BufferedSink bufferedsink) throws IOException {
    entity.writeTo(bufferedsink.outputStream());
  }
}
Exemplo n.º 9
0
  public static void shoploader(final Context context) {
    OkHttpClient okhttp = new OkHttpClient();
    String json = String.format("{\"shop_id\" : \"%s\"}", Omoyo.currentShopId);
    final MediaType JSON = MediaType.parse("application/json;charset=utf-8");
    RequestBody requestbody = RequestBody.create(JSON, json);
    Request request =
        new Request.Builder()
            .url("http://" + context.getResources().getString(R.string.ip) + "/shop/")
            .post(requestbody)
            .build();
    Call call = okhttp.newCall(request);
    call.enqueue(
        new Callback() {
          @Override
          public void onFailure(Request request, IOException e) {}

          @Override
          public void onResponse(Response response) throws IOException {
            if (response.isSuccessful()) {
              String data = response.body().string();
              com.example.muditi.deligoo.Omoyo.edit.putString("shop", data);
              com.example.muditi.deligoo.Omoyo.edit.commit();
            }
          }
        });
  }
Exemplo n.º 10
0
/** Created by Em on 2015/11/26. */
public class ApiRequestBodyConverter<T> implements Converter<T, RequestBody> {
  private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");
  private static final Charset UTF_8 = Charset.forName("UTF-8");

  private final Gson gson;
  private final Type type;

  ApiRequestBodyConverter(Gson gson, Type type) {
    this.gson = gson;
    this.type = type;
  }

  @Override
  public RequestBody convert(T value) throws IOException {
    Buffer buffer = new Buffer();
    Writer writer = new OutputStreamWriter(buffer.outputStream(), UTF_8);
    try {
      gson.toJson(value, type, writer);
      writer.flush();
    } catch (IOException e) {
      throw new AssertionError(e); // Writing to Buffer does no I/O.
    }
    return RequestBody.create(MEDIA_TYPE, buffer.readByteString());
  }
}
Exemplo n.º 11
0
/** Created by zhy on 15/12/14. */
public class PostStringRequest extends OkHttpRequest {
  private static MediaType MEDIA_TYPE_PLAIN = MediaType.parse("text/plain;charset=utf-8");

  private String content;
  private MediaType mediaType;

  public PostStringRequest(
      String url,
      Object tag,
      Map<String, String> params,
      Map<String, String> headers,
      String content,
      MediaType mediaType) {
    super(url, tag, params, headers);
    this.content = content;
    this.mediaType = mediaType;

    if (this.content == null) {
      Exceptions.illegalArgument("the content can not be null !");
    }
    if (this.mediaType == null) {
      this.mediaType = MEDIA_TYPE_PLAIN;
    }
  }

  @Override
  protected RequestBody buildRequestBody() {
    return RequestBody.create(mediaType, content);
  }

  @Override
  protected Request buildRequest(Request.Builder builder, RequestBody requestBody) {
    return builder.post(requestBody).build();
  }
}
Exemplo n.º 12
0
  /**
   * Uploads the image to the server
   *
   * @param b
   * @param listener
   */
  public void uploadImage(final Bitmap b, final OnResponseListener listener) {
    OkHttpClient httpClient = new OkHttpClient();
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    // encode image as PNG, re-encoding as JPG may cause compression artefacts to be visible
    b.compress(Bitmap.CompressFormat.PNG, 0, bos);

    RequestBody requestBody =
        new MultipartBuilder()
            .type(MultipartBuilder.FORM)
            .addPart(
                // the filename parameter is needed to specify that this is indeed a file and not an
                // inline
                // attachment
                Headers.of(
                    "Content-Disposition", "form-data; name=\"image\"; filename=\"image.png\""),
                RequestBody.create(MediaType.parse("image/png"), bos.toByteArray()))
            .build();
    Request request = new Request.Builder().url(UPLOAD_ENDPOINT).post(requestBody).build();

    Call call = httpClient.newCall(request);
    call.enqueue(
        new Callback() {
          @Override
          public void onFailure(Request request, IOException e) {}

          @Override
          public void onResponse(Response response) throws IOException {
            listener.onResponse(new ServerResponse(response.code(), response.body().string()));
          }
        });
  }
Exemplo n.º 13
0
public class StringConverterFactory extends Converter.Factory {
  private static final MediaType MEDIA_TYPE = MediaType.parse("text/plain");

  public static StringConverterFactory create() {
    return new StringConverterFactory();
  }

  @Override
  public Converter<ResponseBody, ?> fromResponseBody(Type type, Annotation[] annotations) {
    if (String.class.equals(type)) {
      return ResponseBody::string;
    }
    return null;
  }

  @Override
  public Converter<?, RequestBody> toRequestBody(Type type, Annotation[] annotations) {
    if (String.class.equals(type)) {
      return new Converter<String, RequestBody>() {
        @Override
        public RequestBody convert(String value) throws IOException {
          return RequestBody.create(MEDIA_TYPE, value);
        }
      };
    }
    return null;
  }
}
Exemplo n.º 14
0
 private static RequestBody convertBody(SmashRequest request, BufferedSource body)
     throws SmashError {
   try {
     return RequestBody.create(MediaType.parse(request.getBodyContentType()), body.readUtf8());
   } catch (IOException ioe) {
     throw new SmashError(ioe);
   }
 }
/** Created by ichiwa on 2015/10/30. */
public class JSONRequestBodyConverter<T> implements Converter<T, RequestBody> {
  private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");

  public JSONRequestBodyConverter() {}

  @Override
  public RequestBody convert(T value) throws IOException {
    return RequestBody.create(MEDIA_TYPE, value.toString());
  }
}
Exemplo n.º 16
0
 /**
  * Serialize the given Java object into request body according to the object's class and the
  * request Content-Type.
  *
  * @param obj The Java object
  * @param contentType The request Content-Type
  * @return The serialized request body
  * @throws ApiException If fail to serialize the given object
  */
 public RequestBody serialize(Object obj, String contentType) throws ApiException {
   if (obj instanceof byte[]) {
     // Binary (byte array) body parameter support.
     return RequestBody.create(MediaType.parse(contentType), (byte[]) obj);
   } else if (obj instanceof File) {
     // File body parameter support.
     return RequestBody.create(MediaType.parse(contentType), (File) obj);
   } else if (isJsonMime(contentType)) {
     String content;
     if (obj != null) {
       content = json.serialize(obj);
     } else {
       content = null;
     }
     return RequestBody.create(MediaType.parse(contentType), content);
   } else {
     throw new ApiException("Content type \"" + contentType + "\" is not supported");
   }
 }
Exemplo n.º 17
0
/** Created by Lukasz Marczak on 2015-07-18. Simple class which posts data to selected url */
public class Post {
  public static final String TAG = Post.class.getSimpleName();
  private OkHttpClient client = new OkHttpClient();

  public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

  public String post(String url, String json) throws IOException {
    RequestBody body = RequestBody.create(JSON, json);
    Request request = new Request.Builder().url(url).put(body).build();
    Response response = client.newCall(request).execute();
    return response.body().string();
  }

  public static final MediaType MEDIA_TYPE_MARKDOWN =
      MediaType.parse("text/x-markdown; charset=utf-8");

  public void postString(String url, String postBody) throws Exception {
    RequestBody body = RequestBody.create(JSON, postBody);
    Request request =
        new Request.Builder()
            .url(url)
            .post(
                /** RequestBody.create(MEDIA_TYPE_MARKDOWN, */
                body)
            .build();

    client
        .newCall(request)
        .enqueue(
            new Callback() {
              @Override
              public void onFailure(Request request, IOException e) {
                Log.e(TAG, "Response isn't succesfull: ");
                e.printStackTrace();
              }

              @Override
              public void onResponse(Response response) throws IOException {
                Log.d(TAG, "Response: " + response.body().string());
              }
            });
  }
}
Exemplo n.º 18
0
 public Response post(String url, byte[] body, StringMap headers, String contentType)
     throws QiniuException {
   RequestBody rbody;
   if (body != null && body.length > 0) {
     MediaType t = MediaType.parse(contentType);
     rbody = RequestBody.create(t, body);
   } else {
     rbody = RequestBody.create(null, new byte[0]);
   }
   return post(url, rbody, headers);
 }
Exemplo n.º 19
0
 public Response multipartPost(
     String url,
     StringMap fields,
     String name,
     String fileName,
     File fileBody,
     String mimeType,
     StringMap headers)
     throws QiniuException {
   RequestBody file = RequestBody.create(MediaType.parse(mimeType), fileBody);
   return multipartPost(url, fields, name, fileName, file, headers);
 }
Exemplo n.º 20
0
  /**
   * Build HTTP call with the given options.
   *
   * @param path The sub-path of the HTTP URL
   * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and
   *     "DELETE"
   * @param queryParams The query parameters
   * @param body The request body object
   * @param headerParams The header parameters
   * @param formParams The form parameters
   * @param authNames The authentications to apply
   * @param progressRequestListener Progress request listener
   * @return The HTTP call
   * @throws ApiException If fail to serialize the request body object
   */
  public Call buildCall(
      String path,
      String method,
      List<Pair> queryParams,
      Object body,
      Map<String, String> headerParams,
      Map<String, Object> formParams,
      String[] authNames,
      ProgressRequestBody.ProgressRequestListener progressRequestListener)
      throws ApiException {
    updateParamsForAuth(authNames, queryParams, headerParams);

    final String url = buildUrl(path, queryParams);
    final Request.Builder reqBuilder = new Request.Builder().url(url);
    processHeaderParams(headerParams, reqBuilder);

    String contentType = (String) headerParams.get("Content-Type");
    // ensuring a default content type
    if (contentType == null) {
      contentType = "application/json";
    }

    RequestBody reqBody;
    if (!HttpMethod.permitsRequestBody(method)) {
      reqBody = null;
    } else if ("application/x-www-form-urlencoded".equals(contentType)) {
      reqBody = buildRequestBodyFormEncoding(formParams);
    } else if ("multipart/form-data".equals(contentType)) {
      reqBody = buildRequestBodyMultipart(formParams);
    } else if (body == null) {
      if ("DELETE".equals(method)) {
        // allow calling DELETE without sending a request body
        reqBody = null;
      } else {
        // use an empty request body (for POST, PUT and PATCH)
        reqBody = RequestBody.create(MediaType.parse(contentType), "");
      }
    } else {
      reqBody = serialize(body, contentType);
    }

    Request request = null;

    if (progressRequestListener != null && reqBody != null) {
      ProgressRequestBody progressRequestBody =
          new ProgressRequestBody(reqBody, progressRequestListener);
      request = reqBuilder.method(method, progressRequestBody).build();
    } else {
      request = reqBuilder.method(method, reqBody).build();
    }

    return httpClient.newCall(request);
  }
  @SuppressWarnings("deprecation")
  private static void setConnectionParametersForRequest(
      com.squareup.okhttp.Request.Builder builder, Request<?> request)
      throws IOException, AuthFailureError {
    switch (request.getMethod()) {
      case Request.Method.DEPRECATED_GET_OR_POST:
        // Ensure backwards compatibility.
        // Volley assumes a request with a null body is a GET.
        byte[] postBody = request.getPostBody();

        if (postBody != null) {
          builder.post(
              RequestBody.create(MediaType.parse(request.getPostBodyContentType()), postBody));
        }
        break;

      case Request.Method.GET:
        builder.get();
        break;

      case Request.Method.DELETE:
        builder.delete();
        break;

      case Request.Method.POST:
        builder.post(createRequestBody(request));
        break;

      case Request.Method.PUT:
        builder.put(createRequestBody(request));
        break;

      case Request.Method.HEAD:
        builder.head();
        break;

      case Request.Method.OPTIONS:
        builder.method("OPTIONS", null);
        break;

      case Request.Method.TRACE:
        builder.method("TRACE", null);
        break;

      case Request.Method.PATCH:
        builder.patch(createRequestBody(request));
        break;

      default:
        throw new IllegalStateException("Unknown method type.");
    }
  }
 {
     if (mediatype == null)
     {
         throw new NullPointerException("type == null");
     } else
     {
         boundary = bytestring;
         contentType = MediaType.parse((new StringBuilder()).append(mediatype).append("; boundary=").append(bytestring.utf8()).toString());
         partHeaders = Util.immutableList(list);
         partBodies = Util.immutableList(list1);
         return;
     }
 }
  private void uploadRecord(String id) {
    String[] key = {"cmd", "userno", "fileno", "togetherid"};
    String[] value = {"uploadappointinstallsound", userNo, orderId, id};

    MultipartBuilder builder = new MultipartBuilder().type(MultipartBuilder.FORM);
    for (int i = 0; i < key.length; i++) {
      builder.addFormDataPart(key[i], value[i]);
    }

    String fileName = recordFile.getName();
    RequestBody fileBody = RequestBody.create(MediaType.parse(guessMimeType(fileName)), recordFile);
    builder.addFormDataPart("", fileName, fileBody);

    HttpUtils.sendHttpPostRequest(
        builder.build(),
        new HttpCallbackListener() {
          @Override
          public void onFinish(final String response) {
            Log.e("responseVoice", response);
            handler.post(
                new Runnable() {
                  @Override
                  public void run() {
                    if (response.substring(0, 1).equals("E")) {
                      ToastUtil.showToast(DistributeActivity.this, "上传录音失败", Toast.LENGTH_SHORT);
                      pDialog.dismiss();
                    } else {
                      recordFile.delete();
                      recordFile = null;
                      saveInfo(response);
                    }
                  }
                });
          }

          @Override
          public void onError(Exception e) {
            handler.post(
                new Runnable() {
                  @Override
                  public void run() {
                    ToastUtil.showToast(DistributeActivity.this, "与服务器断开连接", Toast.LENGTH_SHORT);
                    pDialog.dismiss();
                  }
                });
          }
        });
  }
Exemplo n.º 24
0
  /**
   * Converts a document and returns an {@link InputStream}.
   *
   * @param document The file to convert
   * @param mediaType Internet media type of the file
   * @param conversionTarget The conversion target to use
   * @param customConfig The additional config params to use
   * @return Converted document in the specified format
   * @see {@link HttpMediaType} for available media types
   */
  private InputStream convertDocument(
      final File document,
      final String mediaType,
      final ConversionTarget conversionTarget,
      final JsonObject customConfig) {

    if (document == null || !document.exists())
      throw new IllegalArgumentException("document cannot be null and must exist");

    if (customConfig == null) throw new NullPointerException("custom config must not be null");

    final String type =
        mediaType != null ? mediaType : ConversionUtils.getMediaTypeFromFile(document);
    if (type == null) {
      throw new RuntimeException("mediaType cannot be null or empty");
    } else if (!ConversionUtils.isValidMediaType(type)) {
      throw new IllegalArgumentException("file with the given media type is not supported");
    }

    final JsonObject configJson = new JsonObject();
    // Do this since we shouldn't mutate customConfig
    for (Map.Entry<String, JsonElement> entry : customConfig.entrySet()) {
      configJson.add(entry.getKey(), entry.getValue());
    }
    // Add or override the conversion target
    configJson.addProperty(CONVERSION_TARGET, conversionTarget.toString());

    final MediaType mType = MediaType.parse(type);
    final RequestBody body =
        new MultipartBuilder()
            .type(MultipartBuilder.FORM)
            .addPart(
                Headers.of(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"config\""),
                RequestBody.create(HttpMediaType.JSON, configJson.toString()))
            .addPart(
                Headers.of(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"file\""),
                RequestBody.create(mType, document))
            .build();

    final Request request =
        RequestBuilder.post(CONVERT_DOCUMENT_PATH)
            .withQuery(VERSION, versionDate)
            .withBody(body)
            .build();

    final Response response = execute(request);
    return ResponseUtil.getInputStream(response);
  }
Exemplo n.º 25
0
    /**
     * Reads an entry from an input stream. A typical entry looks like this:
     *
     * <pre>{@code
     * http://google.com/foo
     * GET
     * 2
     * Accept-Language: fr-CA
     * Accept-Charset: UTF-8
     * HTTP/1.1 200 OK
     * 3
     * Content-Type: image/png
     * Content-Length: 100
     * Cache-Control: max-age=600
     * }</pre>
     *
     * <p>A typical HTTPS file looks like this:
     *
     * <pre>{@code
     * https://google.com/foo
     * GET
     * 2
     * Accept-Language: fr-CA
     * Accept-Charset: UTF-8
     * HTTP/1.1 200 OK
     * 3
     * Content-Type: image/png
     * Content-Length: 100
     * Cache-Control: max-age=600
     *
     * AES_256_WITH_MD5
     * 2
     * base64-encoded peerCertificate[0]
     * base64-encoded peerCertificate[1]
     * -1
     * }</pre>
     *
     * The file is newline separated. The first two lines are the URL and the request method. Next
     * is the number of HTTP Vary request header lines, followed by those lines.
     *
     * <p>Next is the response status line, followed by the number of HTTP response header lines,
     * followed by those lines.
     *
     * <p>HTTPS responses also contain SSL session information. This begins with a blank line, and
     * then a line containing the cipher suite. Next is the length of the peer certificate chain.
     * These certificates are base64-encoded and appear each on their own line. The next line
     * contains the length of the local certificate chain. These certificates are also
     * base64-encoded and appear each on their own line. A length of -1 is used to encode a null
     * array.
     */
    public Entry(Source in) throws IOException {
      try {
        BufferedSource source = Okio.buffer(in);
        url = source.readUtf8LineStrict();
        requestMethod = source.readUtf8LineStrict();
        if (readInt(source) == 1) {
          MediaType contentType = MediaType.parse(source.readUtf8LineStrict());
          int contentLength = readInt(source);
          requestBody = RequestBody.create(contentType, source.readByteArray(contentLength));
        } else {
          requestBody = null;
        }
        Headers.Builder varyHeadersBuilder = new Headers.Builder();
        int varyRequestHeaderLineCount = readInt(source);
        for (int i = 0; i < varyRequestHeaderLineCount; i++) {
          OkHttpAccess.addLenient(varyHeadersBuilder, source.readUtf8LineStrict());
        }
        varyHeaders = varyHeadersBuilder.build();

        StatusLine statusLine = StatusLine.parse(source.readUtf8LineStrict());
        protocol = statusLine.protocol;
        code = statusLine.code;
        message = statusLine.message;
        Headers.Builder responseHeadersBuilder = new Headers.Builder();
        int responseHeaderLineCount = readInt(source);
        for (int i = 0; i < responseHeaderLineCount; i++) {
          OkHttpAccess.addLenient(responseHeadersBuilder, source.readUtf8LineStrict());
        }
        responseHeaders = responseHeadersBuilder.build();

        if (isHttps()) {
          String blank = source.readUtf8LineStrict();
          if (blank.length() > 0) {
            throw new IOException("expected \"\" but was \"" + blank + "\"");
          }
          String cipherSuite = source.readUtf8LineStrict();
          List<Certificate> peerCertificates = readCertificateList(source);
          List<Certificate> localCertificates = readCertificateList(source);
          handshake = Handshake.get(cipherSuite, peerCertificates, localCertificates);
        } else {
          handshake = null;
        }
      } finally {
        in.close();
      }
    }
Exemplo n.º 26
0
 /**
  * Build a multipart (file uploading) request body with the given form parameters, which could
  * contain text fields and file fields.
  *
  * @param formParams Form parameters in the form of Map
  * @return RequestBody
  */
 public RequestBody buildRequestBodyMultipart(Map<String, Object> formParams) {
   MultipartBuilder mpBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);
   for (Entry<String, Object> param : formParams.entrySet()) {
     if (param.getValue() instanceof File) {
       File file = (File) param.getValue();
       Headers partHeaders =
           Headers.of(
               "Content-Disposition",
               "form-data; name=\"" + param.getKey() + "\"; filename=\"" + file.getName() + "\"");
       MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file));
       mpBuilder.addPart(partHeaders, RequestBody.create(mediaType, file));
     } else {
       Headers partHeaders =
           Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"");
       mpBuilder.addPart(
           partHeaders, RequestBody.create(null, parameterToString(param.getValue())));
     }
   }
   return mpBuilder.build();
 }
Exemplo n.º 27
0
 private Response response(DiskLruCache.Snapshot snapshot) throws IOException {
   String contentType = responseHeaders.get("Content-Type");
   Request cacheRequest =
       new Request.Builder()
           .url(url)
           .method(requestMethod, requestBody)
           .headers(varyHeaders)
           .build();
   BufferedSource source = Okio.buffer(snapshot.getSource(RESPONSE_BODY));
   byte[] bodyContent = source.readByteArray();
   MediaType mediaType = contentType == null ? null : MediaType.parse(contentType);
   return new Response.Builder()
       .request(cacheRequest)
       .protocol(protocol)
       .code(code)
       .message(message)
       .headers(responseHeaders)
       .body(new OkHttpUtil.ReusableResponseBody(mediaType, bodyContent))
       .handshake(handshake)
       .build();
 }
Exemplo n.º 28
0
class ToStringConverterFactory implements Converter.Factory {
  private static final MediaType MEDIA_TYPE = MediaType.parse("text/plain");

  @Override
  public Converter get(Type type) {
    if (type != String.class) {
      return null;
    }
    return new StringConverter();
  }

  static class StringConverter implements Converter<Object> {
    @Override
    public String fromBody(ResponseBody body) throws IOException {
      return body.string();
    }

    @Override
    public RequestBody toBody(Object value) {
      return RequestBody.create(MEDIA_TYPE, String.valueOf(value));
    }
  }
}
Exemplo n.º 29
0
  private Response multipartPost(
      String url,
      StringMap fields,
      String name,
      String fileName,
      RequestBody file,
      StringMap headers)
      throws QiniuException {
    final MultipartBuilder mb = new MultipartBuilder();
    mb.addFormDataPart(name, fileName, file);

    fields.forEach(
        new StringMap.Consumer() {
          @Override
          public void accept(String key, Object value) {
            mb.addFormDataPart(key, value.toString());
          }
        });
    mb.type(MediaType.parse("multipart/form-data"));
    RequestBody body = mb.build();
    Request.Builder requestBuilder = new Request.Builder().url(url).post(body);
    return send(requestBuilder, headers);
  }
  private void addPart(MultipartBuilder multipartBuilder, String key, Object o) {
    if (o == null) {
      return;
    }

    if (o instanceof File) {
      File tmp = (File) o;
      String extType = MimeTypeMap.getFileExtensionFromUrl(tmp.getAbsolutePath());
      String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extType);
      if (mimeType == null) {
        mimeType = MIME.get(extType.toLowerCase());
      }
      RequestBody file = RequestBody.create(MediaType.parse(mimeType), tmp);
      multipartBuilder.addFormDataPart(key, tmp.getName(), file);
      Timber.d("Media Type. %s, %s, %s", tmp, mimeType, file.contentType());
    } else if (o instanceof byte[]) {
      byte[] tmp = (byte[]) o;
      RequestBody file = RequestBody.create(MEDIA_TYPE_DEFAULT, tmp);
      multipartBuilder.addFormDataPart(key, byteDataId.incrementAndGet() + "", file);
      Timber.d("Media Type. byte[], %s", file.contentType());
    } else {
      multipartBuilder.addFormDataPart(key, o.toString());
    }
  }