Search in sources :

Example 1 with Headers

use of com.squareup.okhttp.Headers in project incubator-weex by apache.

the class DefaultWebSocketAdapter method connect.

@Override
public void connect(String url, @Nullable final String protocol, EventListener listener) {
    this.eventListener = listener;
    this.wsEventReporter = WSEventReporter.newInstance();
    OkHttpClient okHttpClient = new OkHttpClient();
    Request.Builder builder = new Request.Builder();
    if (protocol != null) {
        builder.addHeader(HEADER_SEC_WEBSOCKET_PROTOCOL, protocol);
    }
    builder.url(url);
    wsEventReporter.created(url);
    Request wsRequest = builder.build();
    WebSocketCall webSocketCall = WebSocketCall.create(okHttpClient, wsRequest);
    try {
        Field field = WebSocketCall.class.getDeclaredField("request");
        field.setAccessible(true);
        Request realRequest = (Request) field.get(webSocketCall);
        Headers wsHeaders = realRequest.headers();
        Map<String, String> headers = new HashMap<>();
        for (String name : wsHeaders.names()) {
            headers.put(name, wsHeaders.values(name).toString());
        }
        wsEventReporter.willSendHandshakeRequest(headers, null);
    } catch (Exception e) {
        e.printStackTrace();
    }
    webSocketCall.enqueue(new WebSocketListener() {

        @Override
        public void onOpen(WebSocket webSocket, Request request, Response response) throws IOException {
            ws = webSocket;
            eventListener.onOpen();
            Headers wsHeaders = response.headers();
            Map<String, String> headers = new HashMap<>();
            for (String name : wsHeaders.names()) {
                headers.put(name, wsHeaders.values(name).toString());
            }
            wsEventReporter.handshakeResponseReceived(response.code(), Status.getStatusText(String.valueOf(response.code())), headers);
        }

        @Override
        public void onMessage(BufferedSource payload, WebSocket.PayloadType type) throws IOException {
            if (type == WebSocket.PayloadType.BINARY) {
                wsEventReporter.frameReceived(payload.readByteArray());
            } else {
                String message = payload.readUtf8();
                eventListener.onMessage(message);
                wsEventReporter.frameReceived(message);
            }
            payload.close();
        }

        @Override
        public void onPong(Buffer payload) {
        }

        @Override
        public void onClose(int code, String reason) {
            eventListener.onClose(code, reason, true);
            wsEventReporter.closed();
        }

        @Override
        public void onFailure(IOException e) {
            e.printStackTrace();
            if (e instanceof EOFException) {
                eventListener.onClose(WebSocketCloseCodes.CLOSE_NORMAL.getCode(), WebSocketCloseCodes.CLOSE_NORMAL.name(), true);
                wsEventReporter.closed();
            } else {
                eventListener.onError(e.getMessage());
                wsEventReporter.frameError(e.getMessage());
            }
        }
    });
}
Also used : Buffer(okio.Buffer) WebSocketListener(com.squareup.okhttp.ws.WebSocketListener) OkHttpClient(com.squareup.okhttp.OkHttpClient) HashMap(java.util.HashMap) Headers(com.squareup.okhttp.Headers) Request(com.squareup.okhttp.Request) IOException(java.io.IOException) IOException(java.io.IOException) EOFException(java.io.EOFException) WebSocket(com.squareup.okhttp.ws.WebSocket) Response(com.squareup.okhttp.Response) Field(java.lang.reflect.Field) WebSocketCall(com.squareup.okhttp.ws.WebSocketCall) EOFException(java.io.EOFException) HashMap(java.util.HashMap) Map(java.util.Map) BufferedSource(okio.BufferedSource)

Example 2 with Headers

use of com.squareup.okhttp.Headers in project blockchain-java-api-client by astarlabs.

the class ApiClient method buildRequestBodyMultipart.

/**
 * 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();
}
Also used : Headers(com.squareup.okhttp.Headers) MediaType(com.squareup.okhttp.MediaType) MultipartBuilder(com.squareup.okhttp.MultipartBuilder) File(java.io.File)

Example 3 with Headers

use of com.squareup.okhttp.Headers in project SimplifyReader by chentao0707.

the class OkHttpStack method performRequest.

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError {
    OkHttpClient client = mClient.clone();
    int timeoutMs = request.getTimeoutMs();
    client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    com.squareup.okhttp.Request.Builder okHttpRequestBuilder = new com.squareup.okhttp.Request.Builder();
    okHttpRequestBuilder.url(request.getUrl());
    Map<String, String> headers = request.getHeaders();
    for (final String name : headers.keySet()) {
        okHttpRequestBuilder.addHeader(name, headers.get(name));
    }
    for (final String name : additionalHeaders.keySet()) {
        okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name));
    }
    setConnectionParametersForRequest(okHttpRequestBuilder, request);
    com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build();
    Call okHttpCall = client.newCall(okHttpRequest);
    Response okHttpResponse = okHttpCall.execute();
    StatusLine responseStatus = new BasicStatusLine(parseProtocol(okHttpResponse.protocol()), okHttpResponse.code(), okHttpResponse.message());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromOkHttpResponse(okHttpResponse));
    Headers responseHeaders = okHttpResponse.headers();
    for (int i = 0, len = responseHeaders.size(); i < len; i++) {
        final String name = responseHeaders.name(i), value = responseHeaders.value(i);
        if (name != null) {
            response.addHeader(new BasicHeader(name, value));
        }
    }
    return response;
}
Also used : Call(com.squareup.okhttp.Call) OkHttpClient(com.squareup.okhttp.OkHttpClient) Headers(com.squareup.okhttp.Headers) Request(com.android.volley.Request) BasicStatusLine(org.apache.http.message.BasicStatusLine) Response(com.squareup.okhttp.Response) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpResponse(org.apache.http.HttpResponse) BasicStatusLine(org.apache.http.message.BasicStatusLine) StatusLine(org.apache.http.StatusLine) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) BasicHeader(org.apache.http.message.BasicHeader)

Example 4 with Headers

use of com.squareup.okhttp.Headers in project yoo_home_Android by culturer.

the class OkHttpStack method responseFromConnection.

private URLHttpResponse responseFromConnection(Response okHttpResponse) throws IOException {
    URLHttpResponse response = new URLHttpResponse();
    // contentStream
    int responseCode = okHttpResponse.code();
    if (responseCode == -1) {
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }
    response.setResponseCode(responseCode);
    response.setResponseMessage(okHttpResponse.message());
    response.setContentStream(okHttpResponse.body().byteStream());
    response.setContentLength(okHttpResponse.body().contentLength());
    response.setContentEncoding(okHttpResponse.header("Content-Encoding"));
    if (okHttpResponse.body().contentType() != null) {
        response.setContentType(okHttpResponse.body().contentType().type());
    }
    // header
    HashMap<String, String> headerMap = new HashMap<>();
    Headers responseHeaders = okHttpResponse.headers();
    for (int i = 0, len = responseHeaders.size(); i < len; i++) {
        final String name = responseHeaders.name(i), value = responseHeaders.value(i);
        if (name != null) {
            headerMap.put(name, value);
        }
    }
    response.setHeaders(headerMap);
    return response;
}
Also used : URLHttpResponse(com.kymjs.rxvolley.http.URLHttpResponse) HashMap(java.util.HashMap) Headers(com.squareup.okhttp.Headers) IOException(java.io.IOException)

Example 5 with Headers

use of com.squareup.okhttp.Headers in project ariADDna by StnetixDevTeam.

the class ApiClient method buildRequestBodyMultipart.

/**
 * 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();
}
Also used : Headers(com.squareup.okhttp.Headers) MediaType(com.squareup.okhttp.MediaType) MultipartBuilder(com.squareup.okhttp.MultipartBuilder) File(java.io.File)

Aggregations

Headers (com.squareup.okhttp.Headers)5 MediaType (com.squareup.okhttp.MediaType)2 MultipartBuilder (com.squareup.okhttp.MultipartBuilder)2 OkHttpClient (com.squareup.okhttp.OkHttpClient)2 Response (com.squareup.okhttp.Response)2 File (java.io.File)2 IOException (java.io.IOException)2 HashMap (java.util.HashMap)2 Request (com.android.volley.Request)1 URLHttpResponse (com.kymjs.rxvolley.http.URLHttpResponse)1 Call (com.squareup.okhttp.Call)1 Request (com.squareup.okhttp.Request)1 WebSocket (com.squareup.okhttp.ws.WebSocket)1 WebSocketCall (com.squareup.okhttp.ws.WebSocketCall)1 WebSocketListener (com.squareup.okhttp.ws.WebSocketListener)1 EOFException (java.io.EOFException)1 Field (java.lang.reflect.Field)1 Map (java.util.Map)1 Buffer (okio.Buffer)1 BufferedSource (okio.BufferedSource)1