Java Code Examples for com.squareup.okhttp.RequestBody

The following are top voted examples for showing how to use com.squareup.okhttp.RequestBody. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Android-nRF-Beacon-for-Eddystone   File: ProximityBeaconImpl.java   Source Code and License 9 votes vote down vote up
@Override
protected Void doInBackground(Void... params) {
  //final String token = GoogleAuthUtil.getToken(mActivity, account, SCOPE);
  getToken();
  Request.Builder requestBuilder = new Request.Builder()
          .header(AUTHORIZATION, BEARER + mToken)
          .url(ENDPOINT + urlPart);
  switch (method) {
    case PUT:
      requestBuilder.put(RequestBody.create(MEDIA_TYPE_JSON, json));
      break;
    case POST:
      requestBuilder.post(RequestBody.create(MEDIA_TYPE_JSON, json));
      break;
    case DELETE:
      requestBuilder.delete(RequestBody.create(MEDIA_TYPE_JSON, json));
      break;
    default: break;
  }
  Request request = requestBuilder.build();
  httpClient.newCall(request).enqueue(new HttpCallback(callback));
  return null;
}
 
Example 2
Project: coner-core-client-java   File: ApiClient.java   Source Code and License 8 votes vote down vote up
/**
 * 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");
    }
}
 
Example 3
Project: afp-api-client   File: ApiClient.java   Source Code and License 7 votes vote down vote up
/**
 * 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");
    }
}
 
Example 4
Project: nifi-swagger-client   File: ApiClient.java   Source Code and License 7 votes vote down vote up
/**
 * 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");
    }
}
 
Example 5
Project: boohee_v5.6   File: Client.java   Source Code and License 7 votes vote down vote up
private void asyncMultipartPost(String url, StringMap fields, ProgressHandler
        progressHandler, String fileName, RequestBody file, CompletionHandler
        completionHandler, CancellationHandler cancellationHandler) {
    if (this.converter != null) {
        url = this.converter.convert(url);
    }
    final MultipartBuilder mb = new MultipartBuilder();
    mb.addFormDataPart("file", fileName, file);
    fields.forEach(new Consumer() {
        public void accept(String key, Object value) {
            mb.addFormDataPart(key, value.toString());
        }
    });
    mb.type(MediaType.parse("multipart/form-data"));
    RequestBody body = mb.build();
    if (progressHandler != null) {
        body = new CountingRequestBody(body, progressHandler, cancellationHandler);
    }
    asyncSend(new Builder().url(url).post(body), null, completionHandler);
}
 
Example 6
Project: find-client-android   File: FindWiFiImpl.java   Source Code and License 6 votes vote down vote up
@Override
protected Void doInBackground(Void... params) {

    try {
        Request.Builder requestBuilder = new Request.Builder()
                .url(serverAddr + urlPart);
        switch (method) {
            case PUT:
                requestBuilder.put(RequestBody.create(MEDIA_TYPE_JSON, json));
                break;
            case POST:
                requestBuilder.post(RequestBody.create(MEDIA_TYPE_JSON, json));
                break;
            case DELETE:
                requestBuilder.delete(RequestBody.create(MEDIA_TYPE_JSON, json));
                break;
            default: break;
        }
        Request request = requestBuilder.build();
        httpClient.newCall(request).enqueue(new HttpCallback(callback));
    } catch (Exception e) {
        Log.e(TAG, "IOException", e);
    }
    return null;
}
 
Example 7
Project: boohee_v5.6   File: bu.java   Source Code and License 6 votes vote down vote up
private void a(boolean z, String str, String str2, Map<String, Object> map, cw cwVar,
               OnFailureCallBack onFailureCallBack) {
    try {
        RequestBody create;
        Builder c = c(str);
        if (z) {
            create = RequestBody.create(a, a((Map) map));
        } else {
            create = RequestBody.create(a, c.a((Map) map).toString());
            c.removeHeader("Authorization");
        }
        c.url(str2).post(create);
        a(c.build(), cwVar, onFailureCallBack);
    } catch (GeneralSecurityException e) {
        if (onFailureCallBack != null) {
            this.d.post(new bv(this, onFailureCallBack));
        }
    }
}
 
Example 8
Project: RoadLab-Pro   File: GoogleAPIHelper.java   Source Code and License 6 votes vote down vote up
public Object createFileSync(String parentId, String filePath) {
    String auth = getAuthStr();
    File file = new File(filePath);
    String mediaType = getFileMime(file);
    long fileLength = file.length();
    MediaType type = MediaType.parse(mediaType);
    RequestBody data = RequestBody.create(type, file);
    DriveFile driveFile = null;
    Object resultObj = null;
    try {
        Response<DriveFile> result = RestClient.getInstance().getApiService().
        uploadGooogleFile(GOOGLE_DRIVE_MEDIA_PARAM, GOOGLE_DRIVE_FILE_FIELDS, mediaType, fileLength, auth, data).execute();
        if (result != null) {
            driveFile = result.body();
        }
        String fileId = null;
        if (driveFile != null) {
            fileId = driveFile.getId();
        }
        if (fileId != null && parentId != null) {
            driveFile = setFileFolderSync(parentId, fileId, file.getName());
        }
        resultObj = driveFile;
    } catch (Exception e) {
        resultObj = e;
        Log.e(TAG, "createFileSync", e);
    }
    return resultObj;
}
 
Example 9
Project: Library-Token-Automation   File: LoginActivity.java   Source Code and License 6 votes vote down vote up
Call post(Callback callback) throws IOException {
    OkHttpClient client = getUnsafeOkHttpClient();
    CookieManager cookieManager = new CookieManager();
    cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    client.setCookieHandler(cookieManager);
    RequestBody requestBody = new FormEncodingBuilder()
            .add("user_id", NetId)
            .add("user_password", password)
            .build();
    Request request = new Request.Builder()
            .url("https://studentmaintenance.webapps.snu.edu.in/students/public/studentslist/studentslist/loginauth")
            .post(requestBody)
            .build();
    Call call = client.newCall(request);
    call.enqueue(callback);
    return call;
}
 
Example 10
Project: Android-nRF-Beacon-for-Eddystone   File: RefreshAccessTokenTask.java   Source Code and License 6 votes vote down vote up
@Override
protected Void doInBackground(Void... params) {

    RequestBody requestBody = new FormEncodingBuilder()
            .add("refresh_token", mRefreshToken)
            .add("client_id", mClientId)
            .add("client_secret", "ADD_YOUR_CLIENT_SECRET")
            .add("grant_type", "refresh_token")
            .build();
    final Request request = new Request.Builder()
            .url(Utils.ACCESS_TOKEN_URL)
            .post(requestBody)
            .build();
    mOkHttpClient.newCall(request).enqueue(new HttpCallback(mCallBack));
    return null;
}
 
Example 11
Project: QiNiuGenertorToken   File: Client.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 12
Project: crowdemotion-api-client-java   File: ApiClient.java   Source Code and License 6 votes vote down vote up
/**
 * 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");
    }
}
 
Example 13
Project: LIO-SDK-API-Integracao-Remota-v1-Java   File: ApiClient.java   Source Code and License 6 votes vote down vote up
/**
 * 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");
    }
}
 
Example 14
Project: tradeshift-platform-sdk   File: ApiClient.java   Source Code and License 6 votes vote down vote up
/**
 * 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");
    }
}
 
Example 15
Project: JOSM-IndoorEditor   File: RequestExecutor.java   Source Code and License 6 votes vote down vote up
public static String callGTMC(String url, String filepath) {
    try {
        // ---
        File zipFile = new File(filepath);

        // Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image
        RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM).addFormDataPart("zipFile", zipFile.getName(), RequestBody.create(MEDIA_TYPE_ZIP, zipFile)).build();
        Request request = new Request.Builder().url(url).post(requestBody).build();
        Response response = client.newCall(request).execute();
        if (!response.isSuccessful())
            throw new IOException("Unexpected code " + response);

        return response.body().string();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }
}
 
Example 16
Project: lbry-android   File: ShapeShift.java   Source Code and License 6 votes vote down vote up
/**
 * Normal Transaction
 *
 * Make a normal exchange and receive with {@code withdrawal} address. The exchange pair is
 * determined from the {@link CoinType}s of {@code refund} and {@code withdrawal}.
 */
public ShapeShiftNormalTx exchange(AbstractAddress withdrawal, AbstractAddress refund)
        throws ShapeShiftException, IOException {

    JSONObject requestJson = new JSONObject();
    try {
        requestJson.put("withdrawal", withdrawal.toString());
        requestJson.put("pair", getPair(refund.getType(), withdrawal.getType()));
        requestJson.put("returnAddress", refund.toString());
        if (apiPublicKey != null) requestJson.put("apiKey", apiPublicKey);
    } catch (JSONException e) {
        throw new ShapeShiftException("Could not create a JSON request", e);
    }

    String apiUrl = getApiUrl(NORMAL_TX_API);
    RequestBody body = RequestBody.create(MEDIA_TYPE_JSON, requestJson.toString());
    Request request = new Request.Builder().url(apiUrl).post(body).build();
    ShapeShiftNormalTx reply = new ShapeShiftNormalTx(getMakeApiCall(request));
    if (!reply.isError) checkAddress(withdrawal, reply.withdrawal);
    return reply;
}
 
Example 17
Project: ktball   File: OkHttpUploadRequest.java   Source Code and License 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 18
Project: artikcloud-java   File: ApiClient.java   Source Code and License 6 votes vote down vote up
/**
 * 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");
    }
}
 
Example 19
Project: codelibrary-java   File: ApiClient.java   Source Code and License 6 votes vote down vote up
/**
 * 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");
    }
}
 
Example 20
Project: xDrip-plus   File: SendFeedBack.java   Source Code and License 6 votes vote down vote up
/**
 * https://github.com/square/okhttp/issues/350
 */
private RequestBody forceContentLength(final RequestBody requestBody) throws IOException {
    final Buffer buffer = new Buffer();
    requestBody.writeTo(buffer);
    return new RequestBody() {
        @Override
        public MediaType contentType() {
            return requestBody.contentType();
        }

        @Override
        public long contentLength() {
            return buffer.size();
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            sink.write(buffer.snapshot());
        }
    };
}
 
Example 21
Project: materialup   File: Api.java   Source Code and License 6 votes vote down vote up
public static RequestBody getSearchBody(String query, int page) {
    try {
        JSONObject object = new JSONObject();
        object.put("indexName", getSearchIndexName());
        object.put("params", "query=" + query + "&hitsPerPage=20&page=" + page);
        JSONArray array = new JSONArray();
        array.put(object);
        JSONObject body = new JSONObject();
        body.put("requests", array);


        return RequestBody.create(MediaType.parse("application/json;charset=utf-8"), body.toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }
    String b = "{\"requests\":[{\"indexName\":\"" + getSearchIndexName() + "\",\"params\":\"\"query=" + query + "&hitsPerPage=20&page=" + page + "\"}]}";
    return RequestBody.create(MediaType.parse("application/json;charset=utf-8"), b);
}
 
Example 22
Project: xDrip   File: SendFeedBack.java   Source Code and License 6 votes vote down vote up
/**
 * https://github.com/square/okhttp/issues/350
 */
private RequestBody forceContentLength(final RequestBody requestBody) throws IOException {
    final Buffer buffer = new Buffer();
    requestBody.writeTo(buffer);
    return new RequestBody() {
        @Override
        public MediaType contentType() {
            return requestBody.contentType();
        }

        @Override
        public long contentLength() {
            return buffer.size();
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            sink.write(buffer.snapshot());
        }
    };
}
 
Example 23
Project: xDrip   File: SendFeedBack.java   Source Code and License 6 votes vote down vote up
private RequestBody gzip(final RequestBody body) {
    return new RequestBody() {
        @Override
        public MediaType contentType() {
            return body.contentType();
        }

        @Override
        public long contentLength() {
            return -1; // We don't know the compressed length in advance!
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
            body.writeTo(gzipSink);
            gzipSink.close();
        }
    };
}
 
Example 24
Project: guokr-android   File: EditorModelImpl.java   Source Code and License 6 votes vote down vote up
/**
 * 所有上传图片方式的最终调用的函数。
 * @param data
 */
private void uploadPicture(byte[] data) {
    if (!userModel.checkLoggedIn()) {
        return;
    }

    Thumbnail thumbnail = new Thumbnail();
    thumbnail.bitmap = createThumbnail(data);
    addThumbnail(thumbnail);

    uploadingImages.put(thumbnail, data);

    final String url = "http://www.guokr.com/apis/image.json?enable_watermark=%b";
    new MultipartRequest.Builder<>(url, ImageResult.class)
            .setUrlArgs(preferenceModel.isWatermarkEnable())
            .addFormDataPart("access_token", userModel.getToken())
            .addFormDataPart("upload_file", String.valueOf(Arrays.hashCode(data)),
                    RequestBody.create(MediaType.parse("image/*"), data))
            .setParseListener(response -> cacheImage(response.result.url, data))
            .setListener(response -> onUploadImageSucceed(thumbnail, response.result.url))
            .setErrorListener(error -> onLoadImageFailed(thumbnail))
            .setTag(thumbnail)
            .build(networkModel);
}
 
Example 25
Project: Rocket.Chat-android   File: Meteor.java   Source Code and License 6 votes vote down vote up
/**
 * Sends a string over the websocket
 *
 * @param message the string to send
 */
private void send(String callId, final String message) {
    if (message == null) {
        throw new RuntimeException("You cannot send `null` messages");
    }

    try {
        Timber.d("-->" + message);
        synchronized (mConnection) {
            RequestBody request = RequestBody.create(WebSocket.TEXT, message);
            mConnection.sendMessage(request);
        }
    } catch (Exception e) {
        final Listener listener = mListeners.remove(callId);
        if (listener != null) {
            if (listener instanceof ResultListener) {
                ((ResultListener) listener).onError(new MeteorException(e));
            }
        }
        if (mCallback != null) {
            mCallback.onException(e);
        }
    }
}
 
Example 26
Project: AyoSunny   File: XgoHttpClient.java   Source Code and License 6 votes vote down vote up
/**
 * 初始化Body类型请求参数
 * init Body type params
 */
private RequestBody initRequestBody(TreeMap<String , Object> params) {
    MultipartBuilder bodyBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);
    Set<Map.Entry<String, Object>> entries = params.entrySet();
    for (Map.Entry<String, Object> entry : entries) {
        String key = entry.getKey();
        Object value = entry.getValue();

        if (value instanceof File) {
            File file = (File) value;
            try {
                FileNameMap fileNameMap = URLConnection.getFileNameMap();
                String mimeType = fileNameMap.getContentTypeFor(file.getAbsolutePath());
                XgoLog.w("mimeType::" + mimeType);
                bodyBuilder.addFormDataPart(key, file.getName(), RequestBody.create(MediaType.parse(mimeType), file));
            } catch (Exception e) {
                e.printStackTrace();
                XgoLog.e("mimeType is Error !");
            }
        } else {
            XgoLog.w(key + "::" + value);
            bodyBuilder.addFormDataPart(key, value.toString());
        }
    }
    return bodyBuilder.build();
}
 
Example 27
Project: martian-java   File: Client.java   Source Code and License 6 votes vote down vote up
/**
 * Configures a running instance of Martian with a modifier. Subsequent
 * calls wil overwrite any previous configurations.
 *
 * @param  modifier    Martian request or response modifier
 * @throws IOException if an error occurs during input or output
 **/
public void configure(Modifier modifier) throws IOException {
  StringWriter stringWriter = new StringWriter();
  JsonWriter writer = new JsonWriter(stringWriter);
  modifier.writeJson(writer);

  RequestBody body = RequestBody.create(JSON, stringWriter.toString());
  Request request =
      new Request.Builder().url(getMartianUrl(this.configurePath)).post(body).build();

  Response response = this.client.newCall(request).execute();
  response.body().close();
  if (!response.isSuccessful()) {
    throw new IOException("Error on POST " + this.configurePath + ": " + response);
  }
}
 
Example 28
Project: ariADDna   File: ApiClient.java   Source Code and License 6 votes vote down vote up
/**
 * 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");
    }
}
 
Example 29
Project: triglav-client-java   File: ApiClient.java   Source Code and License 6 votes vote down vote up
/**
 * 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");
    }
}
 
Example 30
Project: Logistics-guard   File: OkHttpClientManager.java   Source Code and License 5 votes vote down vote up
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();
}
 
Example 31
Project: Logistics-guard   File: OkHttpClientManager.java   Source Code and License 5 votes vote down vote up
private Request buildPostRequest(String url, Param[] params) {
    if (params == null) {
        params = new Param[0];
    }
    FormEncodingBuilder builder = new FormEncodingBuilder();
    for (Param param : params) {
        builder.add(param.key, param.value);
    }
    RequestBody requestBody = builder.build();
    return new Request.Builder()
            .url(url)
            .post(requestBody)
            .build();
}
 
Example 32
Project: rkt-launcher   File: ClientTest.java   Source Code and License 5 votes vote down vote up
@Test
public void shouldSendPostRequest() throws ExecutionException, InterruptedException {
  final Request request = new com.squareup.okhttp.Request.Builder()
      .url(URI)
      .method("POST", RequestBody.create(CONTENT_TYPE, "{}"))
      .build();
  when(okHttpClient.newCall(argThat(new RequestMatcher(request)))).thenReturn(call);
  doAnswer(invocation -> {
    final Callback callback = invocation.getArgument(0);
    callback.onResponse(new Response.Builder()
                            .request(request)
                            .protocol(Protocol.HTTP_1_1)
                            .code(Status.OK.code())
                            .message("OK")
                            .body(ResponseBody.create(CONTENT_TYPE, "{}"))
                            .header("foo", "bar")
                            .build());
    return Void.TYPE;
  }).when(call).enqueue(isA(Callback.class));
  final com.spotify.apollo.Response<ByteString> response =
      client.send(com.spotify.apollo.Request
                      .forUri(URI, "POST")
                      .withPayload(ByteString.of("{}".getBytes())))
          .toCompletableFuture().get();
  verify(okHttpClient, never()).setReadTimeout(anyLong(), any());

  assertEquals(Optional.of(ByteString.of("{}".getBytes())), response.payload());
  assertEquals(Optional.of("bar"), response.header("foo"));
}
 
Example 33
Project: afp-api-client   File: ApiClient.java   Source Code and License 5 votes vote down vote up
/**
 * Build a form-encoding request body with the given form parameters.
 *
 * @param formParams Form parameters in the form of Map
 * @return RequestBody
 */
public RequestBody buildRequestBodyFormEncoding(Map<String, Object> formParams) {
    FormEncodingBuilder formBuilder  = new FormEncodingBuilder();
    for (Entry<String, Object> param : formParams.entrySet()) {
        formBuilder.add(param.getKey(), parameterToString(param.getValue()));
    }
    return formBuilder.build();
}
 
Example 34
Project: Raffler-Android   File: ChatActivity.java   Source Code and License 5 votes vote down vote up
Call post(String url, String json, Callback callback) {
    RequestBody body = RequestBody.create(JSON, json);
    Request request = new Request.Builder()
            .addHeader("Content-Type","application/json")
            .addHeader("Authorization","key=AIzaSyAkeFnKc_r6TJSO7tm5OVnzkbni6dEk4Lw")
            .url(url)
            .post(body)
            .build();
    Call call = client.newCall(request);
    call.enqueue(callback);
    return call;
}
 
Example 35
Project: coner-core-client-java   File: ApiClient.java   Source Code and License 5 votes vote down vote up
/**
 * Build a form-encoding request body with the given form parameters.
 *
 * @param formParams Form parameters in the form of Map
 * @return RequestBody
 */
public RequestBody buildRequestBodyFormEncoding(Map<String, Object> formParams) {
    FormEncodingBuilder formBuilder  = new FormEncodingBuilder();
    for (Entry<String, Object> param : formParams.entrySet()) {
        formBuilder.add(param.getKey(), parameterToString(param.getValue()));
    }
    return formBuilder.build();
}
 
Example 36
Project: robird-reborn   File: TweetMarkerUtils.java   Source Code and License 5 votes vote down vote up
public static long save(String collection, long lastRead, String user, OAuthAuthorization oauth) {
    try {
        collection = "lists." + Long.parseLong(collection);
    } catch (NumberFormatException ignored) {

    }

    try {
        final String auth = generateVerifyCredentialsAuthorizationHeader(TWITTER_VERIFY_CREDENTIALS_JSON, oauth);

        JSONObject body = new JSONObject();
        JSONObject collectionJson = new JSONObject();
        collectionJson.put("id", lastRead);
        body.put(collection, collectionJson);

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

        Request request = new Request.Builder()
                .url(TWEETMARKER_API_URL + "?api_key=" + API_KEY + "&username=" + user)
                .addHeader("X-Auth-Service-Provider", TWITTER_VERIFY_CREDENTIALS_JSON)
                .addHeader("X-Verify-Credentials-Authorization", auth)
                .post(RequestBody.create(JSON, body.toString()))
                .build();

        final Response response = createHttpClientWithoutSSL().newCall(request).execute();
        if (response.isSuccessful()) return lastRead;
    } catch (JSONException | IOException | KeyManagementException | NoSuchAlgorithmException e) {
        Timber.i(e, "");
    }

    return -1;
}
 
Example 37
Project: nifi-swagger-client   File: ApiClient.java   Source Code and License 5 votes vote down vote up
/**
 * Build a form-encoding request body with the given form parameters.
 *
 * @param formParams Form parameters in the form of Map
 * @return RequestBody
 */
public RequestBody buildRequestBodyFormEncoding(Map<String, Object> formParams) {
    FormEncodingBuilder formBuilder  = new FormEncodingBuilder();
    for (Entry<String, Object> param : formParams.entrySet()) {
        formBuilder.add(param.getKey(), parameterToString(param.getValue()));
    }
    return formBuilder.build();
}
 
Example 38
Project: boohee_v5.6   File: bu.java   Source Code and License 5 votes vote down vote up
private void c(String str, Map<String, Object> map, cw cwVar, OnFailureCallBack
        onFailureCallBack) {
    try {
        a(c().url(str).put(RequestBody.create(a, a((Map) map))).build(), cwVar,
                onFailureCallBack);
    } catch (GeneralSecurityException e) {
        this.d.post(new cg(this, onFailureCallBack));
    }
}
 
Example 39
Project: boohee_v5.6   File: bu.java   Source Code and License 5 votes vote down vote up
public void b(File file, cw cwVar, OnFailureCallBack onFailureCallBack) {
    file.exists();
    a(new Builder().url("https://eco-api-upload.meiqia.com/upload").post(new MultipartBuilder
            ().type(MultipartBuilder.FORM).addFormDataPart("file", "file.amr", RequestBody
            .create(MediaType.parse("audio/amr"), file)).build()).build(), new cs(this,
            cwVar), onFailureCallBack);
}
 
Example 40
Project: boohee_v5.6   File: Client.java   Source Code and License 5 votes vote down vote up
public void asyncPost(String url, byte[] body, int offset, int size, StringMap headers,
                      ProgressHandler progressHandler, CompletionHandler completionHandler,
                      CancellationHandler c) {
    RequestBody rbody;
    RequestBody rbody2;
    if (this.converter != null) {
        url = this.converter.convert(url);
    }
    if (body == null || body.length <= 0) {
        rbody = RequestBody.create(null, new byte[0]);
    } else {
        rbody = RequestBody.create(MediaType.parse("application/octet-stream"), body, offset,
                size);
    }
    if (progressHandler != null) {
        rbody2 = new CountingRequestBody(rbody, progressHandler, c);
    } else {
        rbody2 = rbody;
    }
    asyncSend(new Builder().url(url).post(rbody2), headers, completionHandler);
}