Search in sources :

Example 96 with Headers

use of okhttp3.Headers in project okhttp-OkGo by jeasonlzy.

the class PostTextActivity method postJson.

@OnClick(R.id.postJson)
public void postJson(View view) {
    HashMap<String, String> params = new HashMap<>();
    params.put("key1", "value1");
    params.put("key2", "这里是需要提交的json格式数据");
    params.put("key3", "也可以使用三方工具将对象转成json字符串");
    params.put("key4", "其实你怎么高兴怎么写都行");
    JSONObject jsonObject = new JSONObject(params);
    //
    OkGo.post(Urls.URL_TEXT_UPLOAD).tag(//
    this).headers("header1", //
    "headerValue1").upJson(//
    jsonObject).execute(new DialogCallback<LzyResponse<ServerModel>>(this) {

        @Override
        public void onSuccess(LzyResponse<ServerModel> responseData, Call call, Response response) {
            handleResponse(responseData.data, call, response);
        }

        @Override
        public void onError(Call call, Response response, Exception e) {
            super.onError(call, response, e);
            handleError(call, response);
        }
    });
}
Also used : LzyResponse(com.lzy.demo.model.LzyResponse) Response(okhttp3.Response) Call(okhttp3.Call) LzyResponse(com.lzy.demo.model.LzyResponse) JSONObject(org.json.JSONObject) ServerModel(com.lzy.demo.model.ServerModel) HashMap(java.util.HashMap) OnClick(butterknife.OnClick)

Example 97 with Headers

use of okhttp3.Headers in project Parse-SDK-Android by ParsePlatform.

the class ParseOkHttpClient method getRequest.

@Override
/* package */
Request getRequest(ParseHttpRequest parseRequest) throws IOException {
    Request.Builder okHttpRequestBuilder = new Request.Builder();
    ParseHttpRequest.Method method = parseRequest.getMethod();
    // Set method
    switch(method) {
        case GET:
            okHttpRequestBuilder.get();
            break;
        case DELETE:
            okHttpRequestBuilder.delete();
            break;
        case POST:
        case PUT:
            // the following.
            break;
        default:
            // ParseRequest.newRequest().
            throw new IllegalStateException("Unsupported http method " + method.toString());
    }
    // Set url
    okHttpRequestBuilder.url(parseRequest.getUrl());
    // Set Header
    Headers.Builder okHttpHeadersBuilder = new Headers.Builder();
    for (Map.Entry<String, String> entry : parseRequest.getAllHeaders().entrySet()) {
        okHttpHeadersBuilder.add(entry.getKey(), entry.getValue());
    }
    // OkHttp automatically add gzip header so we do not need to deal with it
    Headers okHttpHeaders = okHttpHeadersBuilder.build();
    okHttpRequestBuilder.headers(okHttpHeaders);
    // Set Body
    ParseHttpBody parseBody = parseRequest.getBody();
    ParseOkHttpRequestBody okHttpRequestBody = null;
    if (parseBody != null) {
        okHttpRequestBody = new ParseOkHttpRequestBody(parseBody);
    }
    switch(method) {
        case PUT:
            okHttpRequestBuilder.put(okHttpRequestBody);
            break;
        case POST:
            okHttpRequestBuilder.post(okHttpRequestBody);
            break;
    }
    return okHttpRequestBuilder.build();
}
Also used : ParseHttpRequest(com.parse.http.ParseHttpRequest) Headers(okhttp3.Headers) ParseHttpBody(com.parse.http.ParseHttpBody) Request(okhttp3.Request) ParseHttpRequest(com.parse.http.ParseHttpRequest) HashMap(java.util.HashMap) Map(java.util.Map)

Example 98 with Headers

use of okhttp3.Headers in project Parse-SDK-Android by ParsePlatform.

the class ParseOkHttpClient method getResponse.

@Override
/* package */
ParseHttpResponse getResponse(Response okHttpResponse) throws IOException {
    // Status code
    int statusCode = okHttpResponse.code();
    // Content
    InputStream content = okHttpResponse.body().byteStream();
    // Total size
    int totalSize = (int) okHttpResponse.body().contentLength();
    // Reason phrase
    String reasonPhrase = okHttpResponse.message();
    // Headers
    Map<String, String> headers = new HashMap<>();
    for (String name : okHttpResponse.headers().names()) {
        headers.put(name, okHttpResponse.header(name));
    }
    // Content type
    String contentType = null;
    ResponseBody body = okHttpResponse.body();
    if (body != null && body.contentType() != null) {
        contentType = body.contentType().toString();
    }
    return new ParseHttpResponse.Builder().setStatusCode(statusCode).setContent(content).setTotalSize(totalSize).setReasonPhrase(reasonPhrase).setHeaders(headers).setContentType(contentType).build();
}
Also used : HashMap(java.util.HashMap) InputStream(java.io.InputStream) ResponseBody(okhttp3.ResponseBody) ParseHttpResponse(com.parse.http.ParseHttpResponse)

Example 99 with Headers

use of okhttp3.Headers in project Parse-SDK-Android by ParsePlatform.

the class ParseOkHttpClient method addExternalInterceptor.

/**
   * For OKHttpClient, since it does not expose any interface for us to check the raw response
   * stream, we have to use OKHttp networkInterceptors. Instead of using our own interceptor list,
   * we use OKHttp inner interceptor list.
   * @param parseNetworkInterceptor
   */
@Override
/* package */
void addExternalInterceptor(final ParseNetworkInterceptor parseNetworkInterceptor) {
    OkHttpClient.Builder builder = okHttpClient.newBuilder();
    builder.networkInterceptors().add(new Interceptor() {

        @Override
        public Response intercept(final Chain okHttpChain) throws IOException {
            Request okHttpRequest = okHttpChain.request();
            // Transfer OkHttpRequest to ParseHttpRequest
            final ParseHttpRequest parseRequest = getParseHttpRequest(okHttpRequest);
            // Capture OkHttpResponse
            final Capture<Response> okHttpResponseCapture = new Capture<>();
            final ParseHttpResponse parseResponse = parseNetworkInterceptor.intercept(new ParseNetworkInterceptor.Chain() {

                @Override
                public ParseHttpRequest getRequest() {
                    return parseRequest;
                }

                @Override
                public ParseHttpResponse proceed(ParseHttpRequest parseRequest) throws IOException {
                    // Use OKHttpClient to send request
                    Request okHttpRequest = ParseOkHttpClient.this.getRequest(parseRequest);
                    Response okHttpResponse = okHttpChain.proceed(okHttpRequest);
                    okHttpResponseCapture.set(okHttpResponse);
                    return getResponse(okHttpResponse);
                }
            });
            final Response okHttpResponse = okHttpResponseCapture.get();
            // Ideally we should build newOkHttpResponse only based on parseResponse, however
            // ParseHttpResponse does not have all the info we need to build the newOkHttpResponse, so
            // we rely on the okHttpResponse to generate the builder and change the necessary info
            // inside
            Response.Builder newOkHttpResponseBuilder = okHttpResponse.newBuilder();
            // Set status
            newOkHttpResponseBuilder.code(parseResponse.getStatusCode()).message(parseResponse.getReasonPhrase());
            // Set headers
            if (parseResponse.getAllHeaders() != null) {
                for (Map.Entry<String, String> entry : parseResponse.getAllHeaders().entrySet()) {
                    newOkHttpResponseBuilder.header(entry.getKey(), entry.getValue());
                }
            }
            // Set body
            newOkHttpResponseBuilder.body(new ResponseBody() {

                @Override
                public MediaType contentType() {
                    if (parseResponse.getContentType() == null) {
                        return null;
                    }
                    return MediaType.parse(parseResponse.getContentType());
                }

                @Override
                public long contentLength() {
                    return parseResponse.getTotalSize();
                }

                @Override
                public BufferedSource source() {
                    // interceptor.
                    if (parseResponse.getContent() == null) {
                        return null;
                    }
                    return Okio.buffer(Okio.source(parseResponse.getContent()));
                }
            });
            return newOkHttpResponseBuilder.build();
        }
    });
    okHttpClient = builder.build();
}
Also used : ParseHttpRequest(com.parse.http.ParseHttpRequest) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) ParseHttpRequest(com.parse.http.ParseHttpRequest) IOException(java.io.IOException) Capture(bolts.Capture) ResponseBody(okhttp3.ResponseBody) Response(okhttp3.Response) ParseHttpResponse(com.parse.http.ParseHttpResponse) Interceptor(okhttp3.Interceptor) ParseNetworkInterceptor(com.parse.http.ParseNetworkInterceptor) ParseHttpResponse(com.parse.http.ParseHttpResponse)

Example 100 with Headers

use of okhttp3.Headers in project feign by OpenFeign.

the class FeignTest method whenReturnTypeIsResponseNoErrorHandling.

@Test
public void whenReturnTypeIsResponseNoErrorHandling() {
    Map<String, Collection<String>> headers = new LinkedHashMap<String, Collection<String>>();
    headers.put("Location", Arrays.asList("http://bar.com"));
    final Response response = Response.builder().status(302).reason("Found").headers(headers).body(new byte[0]).build();
    TestInterface api = Feign.builder().client(new // fake client as Client.Default follows redirects.
    Client() {

        public Response execute(Request request, Request.Options options) {
            return response;
        }
    }).target(TestInterface.class, "http://localhost:" + server.getPort());
    assertEquals(api.response().headers().get("Location"), Arrays.asList("http://bar.com"));
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) Collection(java.util.Collection) LinkedHashMap(java.util.LinkedHashMap) Test(org.junit.Test)

Aggregations

Test (org.junit.Test)69 Request (okhttp3.Request)55 Response (okhttp3.Response)50 Headers (okhttp3.Headers)43 MockResponse (okhttp3.mockwebserver.MockResponse)33 IOException (java.io.IOException)32 HttpHeaders (okhttp3.internal.http.HttpHeaders)27 ResponseBody (okhttp3.ResponseBody)25 List (java.util.List)19 RequestBody (okhttp3.RequestBody)19 HashMap (java.util.HashMap)14 Map (java.util.Map)14 ANResponse (com.androidnetworking.common.ANResponse)13 AnalyticsListener (com.androidnetworking.interfaces.AnalyticsListener)13 LinkedHashMap (java.util.LinkedHashMap)13 MediaType (okhttp3.MediaType)13 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)13 ANError (com.androidnetworking.error.ANError)11 HttpURLConnection (java.net.HttpURLConnection)11 JSONObject (org.json.JSONObject)11