Search in sources :

Example 1 with RequestBody

use of org.xutils.http.body.RequestBody in project xUtils3 by wyouflf.

the class BaseParams method getRequestBody.

public RequestBody getRequestBody() throws IOException {
    checkBodyParams();
    if (this.requestBody != null) {
        return this.requestBody;
    }
    RequestBody result = null;
    if (!TextUtils.isEmpty(bodyContent)) {
        result = new StringBody(bodyContent, charset);
    } else if (multipart || fileParams.size() > 0) {
        if (!multipart && fileParams.size() == 1) {
            for (KeyValue kv : fileParams) {
                String contentType = null;
                Object value = kv.value;
                if (value instanceof BodyItemWrapper) {
                    BodyItemWrapper wrapper = (BodyItemWrapper) value;
                    value = wrapper.getValue();
                    contentType = wrapper.getContentType();
                }
                if (value instanceof File) {
                    result = new FileBody((File) value, contentType);
                } else if (value instanceof InputStream) {
                    result = new InputStreamBody((InputStream) value, contentType);
                } else if (value instanceof byte[]) {
                    result = new InputStreamBody(new ByteArrayInputStream((byte[]) value), contentType);
                } else if (value instanceof String) {
                    // invoke addBodyParameter(key, stringValue, contentType)
                    result = new StringBody((String) value, charset);
                    result.setContentType(contentType);
                } else {
                    LogUtil.w("Some params will be ignored for: " + this.toString());
                }
                break;
            }
        } else {
            multipart = true;
            result = new MultipartBody(fileParams, charset);
        }
    } else if (bodyParams.size() > 0) {
        result = new UrlEncodedParamsBody(bodyParams, charset);
    }
    return result;
}
Also used : KeyValue(org.xutils.common.util.KeyValue) FileBody(org.xutils.http.body.FileBody) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) BodyItemWrapper(org.xutils.http.body.BodyItemWrapper) UrlEncodedParamsBody(org.xutils.http.body.UrlEncodedParamsBody) StringBody(org.xutils.http.body.StringBody) ByteArrayInputStream(java.io.ByteArrayInputStream) MultipartBody(org.xutils.http.body.MultipartBody) InputStreamBody(org.xutils.http.body.InputStreamBody) JSONObject(org.json.JSONObject) File(java.io.File) RequestBody(org.xutils.http.body.RequestBody)

Example 2 with RequestBody

use of org.xutils.http.body.RequestBody in project xUtils3 by wyouflf.

the class HttpRequest method sendRequest.

/**
 * invoke via Loader
 *
 * @throws IOException
 */
@Override
@TargetApi(Build.VERSION_CODES.KITKAT)
public void sendRequest() throws Throwable {
    isLoading = false;
    responseCode = 0;
    URL url = new URL(queryUrl);
    {
        // init connection
        Proxy proxy = params.getProxy();
        if (proxy != null) {
            connection = (HttpURLConnection) url.openConnection(proxy);
        } else {
            connection = (HttpURLConnection) url.openConnection();
        }
        // try to fix bug: accidental EOFException before API 19
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            connection.setRequestProperty("Connection", "close");
        }
        connection.setReadTimeout(params.getReadTimeout());
        connection.setConnectTimeout(params.getConnectTimeout());
        connection.setInstanceFollowRedirects(params.getRedirectHandler() == null);
        if (connection instanceof HttpsURLConnection) {
            SSLSocketFactory sslSocketFactory = params.getSslSocketFactory();
            if (sslSocketFactory != null) {
                ((HttpsURLConnection) connection).setSSLSocketFactory(sslSocketFactory);
            }
        }
    }
    if (params.isUseCookie()) {
        // add cookies
        try {
            Map<String, List<String>> singleMap = COOKIE_MANAGER.get(url.toURI(), new HashMap<String, List<String>>(0));
            List<String> cookies = singleMap.get("Cookie");
            if (cookies != null) {
                connection.setRequestProperty("Cookie", TextUtils.join(";", cookies));
            }
        } catch (Throwable ex) {
            LogUtil.e(ex.getMessage(), ex);
        }
    }
    {
        // add headers
        List<RequestParams.Header> headers = params.getHeaders();
        if (headers != null) {
            for (RequestParams.Header header : headers) {
                String name = header.key;
                String value = header.getValueStr();
                if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(value)) {
                    if (header.setHeader) {
                        connection.setRequestProperty(name, value);
                    } else {
                        connection.addRequestProperty(name, value);
                    }
                }
            }
        }
    }
    // intercept response
    if (requestInterceptListener != null) {
        requestInterceptListener.beforeRequest(this);
    }
    {
        // write body
        HttpMethod method = params.getMethod();
        try {
            connection.setRequestMethod(method.toString());
        } catch (ProtocolException ex) {
            try {
                // fix: HttpURLConnection not support PATCH method.
                Field methodField = HttpURLConnection.class.getDeclaredField("method");
                methodField.setAccessible(true);
                methodField.set(connection, method.toString());
            } catch (Throwable ignored) {
                throw ex;
            }
        }
        if (HttpMethod.permitsRequestBody(method)) {
            RequestBody body = params.getRequestBody();
            if (body != null) {
                if (body instanceof ProgressBody) {
                    ((ProgressBody) body).setProgressHandler(progressHandler);
                }
                String contentType = body.getContentType();
                if (!TextUtils.isEmpty(contentType)) {
                    connection.setRequestProperty("Content-Type", contentType);
                }
                long contentLength = body.getContentLength();
                if (contentLength < 0) {
                    connection.setChunkedStreamingMode(256 * 1024);
                } else {
                    if (contentLength < Integer.MAX_VALUE) {
                        connection.setFixedLengthStreamingMode((int) contentLength);
                    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                        connection.setFixedLengthStreamingMode(contentLength);
                    } else {
                        connection.setChunkedStreamingMode(256 * 1024);
                    }
                }
                connection.setRequestProperty("Content-Length", String.valueOf(contentLength));
                connection.setDoOutput(true);
                body.writeTo(connection.getOutputStream());
            }
        }
    }
    if (params.isUseCookie()) {
        // save cookies
        try {
            Map<String, List<String>> headers = connection.getHeaderFields();
            if (headers != null) {
                COOKIE_MANAGER.put(url.toURI(), headers);
            }
        } catch (Throwable ex) {
            LogUtil.e(ex.getMessage(), ex);
        }
    }
    // check response code
    responseCode = connection.getResponseCode();
    // intercept response
    if (requestInterceptListener != null) {
        requestInterceptListener.afterRequest(this);
    }
    if (responseCode == 204 || responseCode == 205) {
        // empty content
        throw new HttpException(responseCode, this.getResponseMessage());
    } else if (responseCode >= 300) {
        HttpException httpException = new HttpException(responseCode, this.getResponseMessage());
        try {
            httpException.setResult(IOUtil.readStr(this.getInputStream(), params.getCharset()));
        } catch (Throwable ignored) {
        }
        LogUtil.e(httpException.toString() + ", url: " + queryUrl);
        throw httpException;
    }
    isLoading = true;
}
Also used : ProtocolException(java.net.ProtocolException) ProgressBody(org.xutils.http.body.ProgressBody) URL(java.net.URL) RequestParams(org.xutils.http.RequestParams) Field(java.lang.reflect.Field) Proxy(java.net.Proxy) HttpURLConnection(java.net.HttpURLConnection) List(java.util.List) HttpException(org.xutils.ex.HttpException) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) HttpMethod(org.xutils.http.HttpMethod) RequestBody(org.xutils.http.body.RequestBody) TargetApi(android.annotation.TargetApi)

Aggregations

RequestBody (org.xutils.http.body.RequestBody)2 TargetApi (android.annotation.TargetApi)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 File (java.io.File)1 InputStream (java.io.InputStream)1 Field (java.lang.reflect.Field)1 HttpURLConnection (java.net.HttpURLConnection)1 ProtocolException (java.net.ProtocolException)1 Proxy (java.net.Proxy)1 URL (java.net.URL)1 List (java.util.List)1 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)1 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)1 JSONObject (org.json.JSONObject)1 KeyValue (org.xutils.common.util.KeyValue)1 HttpException (org.xutils.ex.HttpException)1 HttpMethod (org.xutils.http.HttpMethod)1 RequestParams (org.xutils.http.RequestParams)1 BodyItemWrapper (org.xutils.http.body.BodyItemWrapper)1 FileBody (org.xutils.http.body.FileBody)1