Search in sources :

Example 21 with RequestBody

use of com.squareup.okhttp.RequestBody in project openzaly by akaxincom.

the class HttpClient method postKV.

static String postKV(String url) throws IOException {
    RequestBody formBody = new FormEncodingBuilder().add("platform", "android").add("name", "bug").build();
    Request request = new Request.Builder().url(url).post(formBody).build();
    Response response = client.newCall(request).execute();
    System.out.println("post KV response =" + response.isSuccessful());
    if (response.isSuccessful()) {
        return response.body().string();
    } else {
        throw new IOException("Unexpected code " + response);
    }
}
Also used : Response(com.squareup.okhttp.Response) Request(com.squareup.okhttp.Request) FormEncodingBuilder(com.squareup.okhttp.FormEncodingBuilder) IOException(java.io.IOException) RequestBody(com.squareup.okhttp.RequestBody)

Example 22 with RequestBody

use of com.squareup.okhttp.RequestBody in project openzaly by akaxincom.

the class HttpClient method postJson.

static String postJson(String url, String json) throws IOException {
    MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    RequestBody postBody = RequestBody.create(JSON, json);
    Request request = new Request.Builder().url(url).post(postBody).build();
    Response response = client.newCall(request).execute();
    System.out.println("post postJson response =" + response.isSuccessful());
    if (response.isSuccessful()) {
        return response.body().toString();
    } else {
        System.out.println("http post failed");
        throw new IOException("post json Unexpected code " + response);
    }
}
Also used : Response(com.squareup.okhttp.Response) Request(com.squareup.okhttp.Request) MediaType(com.squareup.okhttp.MediaType) IOException(java.io.IOException) RequestBody(com.squareup.okhttp.RequestBody)

Example 23 with RequestBody

use of com.squareup.okhttp.RequestBody in project hale by halestudio.

the class ProjectStoreHelper method executePlainTextCallWithFeedback.

/**
 * Execute a REST call with the content type <code>text/plain; charset=utf-8
 * </code>
 *
 * @param method HTTP method (POST, PUT)
 * @param path REST path (without base path)
 * @param body The plain text bdoy
 * @param basePath The REST base path
 * @param apiKey The API key
 * @return the feedback
 * @throws HaleConnectException thrown on any API error
 */
public static Feedback executePlainTextCallWithFeedback(String method, String path, String body, BasePathResolver basePath, String apiKey) throws HaleConnectException {
    ApiClient apiClient = ProjectStoreHelper.getApiClient(basePath, apiKey);
    OkHttpClient httpClient = apiClient.getHttpClient();
    String url = apiClient.buildUrl(path, null);
    Request.Builder reqBuilder = new Request.Builder().url(url);
    Map<String, String> headerParams = new HashMap<String, String>();
    apiClient.updateParamsForAuth(new String[] { "bearer" }, null, headerParams);
    apiClient.processHeaderParams(headerParams, reqBuilder);
    RequestBody reqBody = RequestBody.create(MediaType.parse("text/plain; charset=utf-8"), body);
    Request request = reqBuilder.method(method, reqBody).build();
    Call call = httpClient.newCall(request);
    Feedback feedback;
    try {
        ApiResponse<Feedback> resp = apiClient.execute(call, new TypeToken<Feedback>() {
        }.getType());
        feedback = resp.getData();
    } catch (com.haleconnect.api.projectstore.v1.ApiException e) {
        throw new HaleConnectException(e.getMessage(), e);
    }
    return feedback;
}
Also used : Call(com.squareup.okhttp.Call) OkHttpClient(com.squareup.okhttp.OkHttpClient) HashMap(java.util.HashMap) Request(com.squareup.okhttp.Request) HaleConnectException(eu.esdihumboldt.hale.io.haleconnect.HaleConnectException) ApiClient(com.haleconnect.api.projectstore.v1.ApiClient) Feedback(com.haleconnect.api.projectstore.v1.model.Feedback) TypeToken(com.google.gson.reflect.TypeToken) RequestBody(com.squareup.okhttp.RequestBody)

Example 24 with RequestBody

use of com.squareup.okhttp.RequestBody in project QuickAndroid by ImKarl.

the class OkHttpCacheHelper method getResponse.

private static Response getResponse(OkHttpClient client, Request request) throws IOException {
    // Copy body metadata to the appropriate request headers.
    RequestBody body = request.body();
    if (body != null) {
        Request.Builder requestBuilder = request.newBuilder();
        MediaType contentType = body.contentType();
        if (contentType != null) {
            requestBuilder.header("Content-Type", contentType.toString());
        }
        long contentLength = body.contentLength();
        if (contentLength != -1) {
            requestBuilder.header("Content-Length", Long.toString(contentLength));
            requestBuilder.removeHeader("Transfer-Encoding");
        } else {
            requestBuilder.header("Transfer-Encoding", "chunked");
            requestBuilder.removeHeader("Content-Length");
        }
        request = requestBuilder.build();
    }
    copyWithDefaults(client);
    // Create the initial HTTP engine. Retries and redirects need new engine
    // for each attempt.
    HttpEngine engine = new HttpEngine(client, request, false, false, false, null, null, null, null);
    int followUpCount = 0;
    while (true) {
        try {
            engine.sendRequest();
            engine.readResponse();
        } catch (RequestException e) {
            // The attempt to interpret the request failed. Give up.
            throw e.getCause();
        } catch (RouteException e) {
            // The attempt to connect via a route failed. The request will
            // not have been sent.
            HttpEngine retryEngine = engine.recover(e);
            if (retryEngine != null) {
                engine = retryEngine;
                continue;
            }
            // Give up; recovery is not possible.
            throw e.getLastConnectException();
        } catch (IOException e) {
            // An attempt to communicate with a server failed. The request
            // may have been sent.
            HttpEngine retryEngine = engine.recover(e, null);
            if (retryEngine != null) {
                engine = retryEngine;
                continue;
            }
            // Give up; recovery is not possible.
            throw e;
        }
        Response response = engine.getResponse();
        Request followUp = engine.followUpRequest();
        if (followUp == null) {
            return response;
        }
        if (++followUpCount > MAX_FOLLOW_UPS) {
            throw new ProtocolException("Too many follow-up requests: " + followUpCount);
        }
        if (!engine.sameConnection(followUp.httpUrl())) {
            engine.releaseConnection();
        }
        Connection connection = engine.close();
        request = followUp;
        engine = new HttpEngine(client, request, false, false, false, connection, null, null, response);
    }
}
Also used : RouteException(com.squareup.okhttp.internal.http.RouteException) ProtocolException(java.net.ProtocolException) HttpEngine(com.squareup.okhttp.internal.http.HttpEngine) Request(com.squareup.okhttp.Request) Connection(com.squareup.okhttp.Connection) IOException(java.io.IOException) RequestException(com.squareup.okhttp.internal.http.RequestException) Response(com.squareup.okhttp.Response) MediaType(com.squareup.okhttp.MediaType) RequestBody(com.squareup.okhttp.RequestBody)

Example 25 with RequestBody

use of com.squareup.okhttp.RequestBody in project QuickAndroid by ImKarl.

the class OkHttp method createRequest.

private <T> Request createRequest(QAHttpMethod method, String url, QARequestParams params, final QAHttpCallback<T> listener) {
    if (method == null) {
        method = QAHttpMethod.GET;
    }
    final String finalUrl = url;
    if (method == QAHttpMethod.GET) {
        url = parseGetUrl(url, params != null ? params.getParams() : null);
        params = null;
    } else {
        if (params == null) {
            params = new QARequestParams();
        }
    }
    Request.Builder builder = new Request.Builder();
    try {
        builder.url(url);
    } catch (final Exception e) {
        sendFailedCallback(finalUrl, e, listener);
        return null;
    }
    // 强制使用缓存
    builder.cacheControl(CacheControl.FORCE_CACHE);
    // header
    Headers.Builder headerBuilder = new Headers.Builder();
    if (params != null && !params.getHeaders().isEmpty()) {
        for (Entry<String, String> entry : params.getHeaders().entrySet()) {
            headerBuilder.add(entry.getKey(), entry.getValue());
        }
    }
    builder.headers(headerBuilder.build());
    // param
    RequestBody requestBody = null;
    if (params != null) {
        if (!TextUtils.isEmpty(params.getBody())) {
            requestBody = RequestBody.create(MEDIA_TYPE_TEXT, params.getBody());
        } else {
            try {
                MultipartBuilder paramBuilder = new MultipartBuilder();
                if (params != null && !params.getParams().isEmpty()) {
                    for (Entry<String, List<Part>> entry : params.getParams().entrySet()) {
                        String name = entry.getKey();
                        List<Part> parts = entry.getValue();
                        if (parts != null && !parts.isEmpty()) {
                            for (Part part : parts) {
                                paramBuilder.addPart(part.header(), part.body());
                            }
                        }
                    }
                }
                requestBody = paramBuilder.build();
            } catch (IllegalStateException e) {
                requestBody = new FormEncodingBuilder().build();
            }
        }
    }
    builder.method(method.name(), requestBody == null ? null : new ProgressRequestBody(requestBody, new OnProgressListener() {

        @Override
        public void onProgress(long currentBytes, long contentLength) {
            // 上传进度
            sendProgressCallback(finalUrl, currentBytes, contentLength, QAHttpAction.REQUEST, listener);
        }
    }));
    final Request request = builder.build();
    mOnProgressListeners.put(request, new OnProgressListener() {

        @Override
        public void onProgress(long currentBytes, long contentLength) {
            // 下载进度
            sendProgressCallback(finalUrl, currentBytes, contentLength, QAHttpAction.RESPONSE, listener);
        }
    });
    return request;
}
Also used : Headers(com.squareup.okhttp.Headers) FormEncodingBuilder(com.squareup.okhttp.FormEncodingBuilder) MultipartBuilder(com.squareup.okhttp.MultipartBuilder) Request(com.squareup.okhttp.Request) FormEncodingBuilder(com.squareup.okhttp.FormEncodingBuilder) QANullException(cn.jeesoft.qa.error.QANullException) QANoSupportException(cn.jeesoft.qa.error.QANoSupportException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) QAException(cn.jeesoft.qa.error.QAException) IOException(java.io.IOException) StringPart(cn.jeesoft.qa.libcore.http.part.StringPart) Part(cn.jeesoft.qa.libcore.http.part.Part) List(java.util.List) MultipartBuilder(com.squareup.okhttp.MultipartBuilder) QARequestParams(cn.jeesoft.qa.libcore.http.QARequestParams) RequestBody(com.squareup.okhttp.RequestBody)

Aggregations

RequestBody (com.squareup.okhttp.RequestBody)39 Request (com.squareup.okhttp.Request)33 Response (com.squareup.okhttp.Response)24 IOException (java.io.IOException)19 OkHttpClient (com.squareup.okhttp.OkHttpClient)14 FormEncodingBuilder (com.squareup.okhttp.FormEncodingBuilder)12 BufferedSink (okio.BufferedSink)7 MultipartBuilder (com.squareup.okhttp.MultipartBuilder)4 UnsupportedEncodingException (java.io.UnsupportedEncodingException)4 Call (com.squareup.okhttp.Call)3 Buffer (okio.Buffer)3 Activity (android.app.Activity)2 PowerManager (android.os.PowerManager)2 AppCompatActivity (android.support.v7.app.AppCompatActivity)2 EditText (android.widget.EditText)2 BaseAppCompatActivity (com.eveningoutpost.dexdrip.BaseAppCompatActivity)2 MediaType (com.squareup.okhttp.MediaType)2 CookieManager (java.net.CookieManager)2 GzipSink (okio.GzipSink)2 ApiCallException (org.eyeseetea.malariacare.domain.exception.ApiCallException)2