當前位置: 首頁>>代碼示例>>Java>>正文


Java RequestBody類代碼示例

本文整理匯總了Java中com.squareup.okhttp.RequestBody的典型用法代碼示例。如果您正苦於以下問題:Java RequestBody類的具體用法?Java RequestBody怎麽用?Java RequestBody使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


RequestBody類屬於com.squareup.okhttp包,在下文中一共展示了RequestBody類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: doInBackground

import com.squareup.okhttp.RequestBody; //導入依賴的package包/類
@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;
}
 
開發者ID:NordicSemiconductor,項目名稱:Android-nRF-Beacon-for-Eddystone,代碼行數:24,代碼來源:ProximityBeaconImpl.java

示例2: serialize

import com.squareup.okhttp.RequestBody; //導入依賴的package包/類
/**
 * 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");
    }
}
 
開發者ID:caeos,項目名稱:coner-core-client-java,代碼行數:29,代碼來源:ApiClient.java

示例3: asyncMultipartPost

import com.squareup.okhttp.RequestBody; //導入依賴的package包/類
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);
}
 
開發者ID:JackChan1999,項目名稱:boohee_v5.6,代碼行數:21,代碼來源:Client.java

示例4: doInBackground

import com.squareup.okhttp.RequestBody; //導入依賴的package包/類
@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;
}
 
開發者ID:uncleashi,項目名稱:find-client-android,代碼行數:26,代碼來源:FindWiFiImpl.java

示例5: a

import com.squareup.okhttp.RequestBody; //導入依賴的package包/類
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));
        }
    }
}
 
開發者ID:JackChan1999,項目名稱:boohee_v5.6,代碼行數:20,代碼來源:bu.java

示例6: createFileSync

import com.squareup.okhttp.RequestBody; //導入依賴的package包/類
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;
}
 
開發者ID:WorldBank-Transport,項目名稱:RoadLab-Pro,代碼行數:30,代碼來源:GoogleAPIHelper.java

示例7: post

import com.squareup.okhttp.RequestBody; //導入依賴的package包/類
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;
}
 
開發者ID:anuragsai97,項目名稱:Library-Token-Automation,代碼行數:18,代碼來源:LoginActivity.java

示例8: doInBackground

import com.squareup.okhttp.RequestBody; //導入依賴的package包/類
@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;
}
 
開發者ID:NordicSemiconductor,項目名稱:Android-nRF-Beacon-for-Eddystone,代碼行數:17,代碼來源:RefreshAccessTokenTask.java

示例9: multipartPost

import com.squareup.okhttp.RequestBody; //導入依賴的package包/類
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);
}
 
開發者ID:charsdavy,項目名稱:QiNiuGenertorToken,代碼行數:21,代碼來源:Client.java

示例10: callGTMC

import com.squareup.okhttp.RequestBody; //導入依賴的package包/類
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;
    }
}
 
開發者ID:STEMLab,項目名稱:JOSM-IndoorEditor,代碼行數:20,代碼來源:RequestExecutor.java

示例11: exchange

import com.squareup.okhttp.RequestBody; //導入依賴的package包/類
/**
 * 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;
}
 
開發者ID:filipnyquist,項目名稱:lbry-android,代碼行數:27,代碼來源:ShapeShift.java

示例12: addParams

import com.squareup.okhttp.RequestBody; //導入依賴的package包/類
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)));

        }
    }
}
 
開發者ID:dscn,項目名稱:ktball,代碼行數:18,代碼來源:OkHttpUploadRequest.java

示例13: forceContentLength

import com.squareup.okhttp.RequestBody; //導入依賴的package包/類
/**
 * 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());
        }
    };
}
 
開發者ID:jamorham,項目名稱:xDrip-plus,代碼行數:24,代碼來源:SendFeedBack.java

示例14: getSearchBody

import com.squareup.okhttp.RequestBody; //導入依賴的package包/類
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);
}
 
開發者ID:goodev,項目名稱:materialup,代碼行數:19,代碼來源:Api.java

示例15: gzip

import com.squareup.okhttp.RequestBody; //導入依賴的package包/類
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();
        }
    };
}
 
開發者ID:NightscoutFoundation,項目名稱:xDrip,代碼行數:21,代碼來源:SendFeedBack.java


注:本文中的com.squareup.okhttp.RequestBody類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。