Search in sources :

Example 51 with Cookie

use of okhttp3.Cookie in project spring-framework by spring-projects.

the class WebClientIntegrationTests method cookies.

@Test
public void cookies() throws Exception {
    this.server.enqueue(new MockResponse().setHeader("Content-Type", "text/plain").setBody("test"));
    Mono<String> result = this.webClient.get().uri("/test").cookie("testkey", "testvalue").exchange().then(response -> response.bodyToMono(String.class));
    StepVerifier.create(result).expectNext("test").expectComplete().verify(Duration.ofSeconds(3));
    RecordedRequest recordedRequest = server.takeRequest();
    Assert.assertEquals(1, server.getRequestCount());
    Assert.assertEquals("/test", recordedRequest.getPath());
    Assert.assertEquals("testkey=testvalue", recordedRequest.getHeader(HttpHeaders.COOKIE));
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) Test(org.junit.Test)

Example 52 with Cookie

use of okhttp3.Cookie in project Gradle-demo by Arisono.

the class OkhttpUtilsMain method sendSysResquest.

/**
	 * Okhttp 异步请求
	 */
public static void sendSysResquest() {
    RequestBody formBody = new FormBody.Builder().add("username", "123").add("password", "df13edafsdddsads").build();
    OkHttpClient client = new OkHttpClient.Builder().connectTimeout(5, TimeUnit.SECONDS).readTimeout(5, TimeUnit.SECONDS).build();
    Request request = new Request.Builder().url("http://localhost:8080/spring-mvc-showcase/client/info").header("cookie", "JSESSIONID=EB36DE5E50E342D86C55DAE0CDDD4F6D").addHeader("content-type", "text/html;charset:utf-8").post(formBody).build();
    client.newCall(request).enqueue(new Callback() {

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if (response.isSuccessful()) {
                String json = response.body().string();
                System.out.println(json);
            } else {
                System.out.println(JSON.toJSONString(response.code()));
            }
        }

        @Override
        public void onFailure(Call call, IOException e) {
            System.out.println(ExceptionUtils.printExceptionStack(e));
            if (e instanceof ConnectException) {
                System.out.println("服务器拒绝访问!");
            } else if (e instanceof SocketTimeoutException) {
                System.out.println("超时响应!");
            }
        }
    });
}
Also used : Call(okhttp3.Call) OkHttpClient(okhttp3.OkHttpClient) FormBody(okhttp3.FormBody) Request(okhttp3.Request) IOException(java.io.IOException) Response(okhttp3.Response) Callback(okhttp3.Callback) SocketTimeoutException(java.net.SocketTimeoutException) RequestBody(okhttp3.RequestBody) ConnectException(java.net.ConnectException)

Example 53 with Cookie

use of okhttp3.Cookie in project Gradle-demo by Arisono.

the class OkhttpUtilsMain method sendHeadersAndParams.

/**
	 * 发请求头以及请求参数
	 */
public static void sendHeadersAndParams() {
    String china_str = "";
    try {
        china_str = URLEncoder.encode("中文", "UTF-8");
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
    }
    MediaType MEDIA_TYPE_TEXT = MediaType.parse("text/plain");
    String postBody = "Hello World";
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder().url("http://localhost:8080/spring-mvc-showcase/http/getHeaders").header("cookie", "JSESSIONID=EB36DE5E50E342D86C55DAE0CDDD4F6D").addHeader("content-type", "text/html;charset:utf-8").addHeader("Home", "china").addHeader("Home1", china_str).addHeader("user-agent", "android").put(RequestBody.create(MEDIA_TYPE_TEXT, postBody)).build();
    try {
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            String json = response.body().string();
            System.out.println(json);
            String home1 = JSON.parseObject(json).getJSONObject("headers").getString("home1");
            System.out.println(URLDecoder.decode(home1, "utf-8"));
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Also used : Response(okhttp3.Response) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) UnsupportedEncodingException(java.io.UnsupportedEncodingException) MediaType(okhttp3.MediaType) IOException(java.io.IOException)

Example 54 with Cookie

use of okhttp3.Cookie in project Gradle-demo by Arisono.

the class OkhttpUtilsMain method sendHeaders.

/**
	 * 发请求头
	 */
public static void sendHeaders() {
    String china_str = "";
    try {
        china_str = URLEncoder.encode("中文", "UTF-8");
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
    }
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder().url("http://192.168.253.132:9090/platform-b2c/?client=true").header("cookie", "JSESSIONID=EB36DE5E50E342D86C55DAE0CDDD4F6D").addHeader("content-type", "text/html;charset:utf-8").addHeader("client-name", // 自定义的header
    "uasClient").addHeader("Home1", // 自定义的header 传中�?
    china_str).addHeader("user-agent", "android").build();
    try {
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            String json = response.body().string();
            System.out.println(json);
            String home1 = JSON.parseObject(json).getJSONObject("headers").getString("home1");
            System.out.println(URLDecoder.decode(home1, "utf-8"));
        } else {
            System.out.println(JSON.toJSONString(response.code()));
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Also used : Response(okhttp3.Response) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException)

Example 55 with Cookie

use of okhttp3.Cookie in project Gradle-demo by Arisono.

the class OkhttpUtils method sendPostHttp.

/** 
	 * post http
	 * @param url
	 * @param params
	 * @param tag
	 */
public static void sendPostHttp(String url, Map<String, Object> params, String cookies, String tag) {
    Builder paramBuilder = new FormBody.Builder();
    if (!params.isEmpty()) {
        Iterator<Map.Entry<String, Object>> entries = params.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<String, Object> entry = entries.next();
            paramBuilder.add(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
        }
        OkhttpUtils.println(tag + ":" + url);
        RequestBody formBody = paramBuilder.build();
        Request request = new Request.Builder().url(url).addHeader("content-type", "text/html;charset:utf-8").addHeader("Cookie", cookies).post(formBody).build();
        OkhttpUtils.client.newCall(request).enqueue(new Callback() {

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String requestJson = OkhttpUtils.getResponseString(response);
                RxBus.getInstance().send(tag + ":" + requestJson);
            }

            @Override
            public void onFailure(Call call, IOException e) {
                OkhttpUtils.onFailurePrintln(call, e, this);
            }
        });
    }
}
Also used : Call(okhttp3.Call) Builder(okhttp3.FormBody.Builder) Request(okhttp3.Request) IOException(java.io.IOException) Response(okhttp3.Response) Callback(okhttp3.Callback) Map(java.util.Map) RequestBody(okhttp3.RequestBody)

Aggregations

Response (okhttp3.Response)34 IOException (java.io.IOException)33 Request (okhttp3.Request)33 Call (okhttp3.Call)25 Callback (okhttp3.Callback)22 RequestBody (okhttp3.RequestBody)21 Test (org.junit.Test)18 Cookie (okhttp3.Cookie)17 MockResponse (okhttp3.mockwebserver.MockResponse)16 FormBody (okhttp3.FormBody)12 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)10 CookieManager (java.net.CookieManager)9 HttpCookie (java.net.HttpCookie)9 MockWebServer (okhttp3.mockwebserver.MockWebServer)8 OkHttpClient (okhttp3.OkHttpClient)6 ArrayList (java.util.ArrayList)5 Map (java.util.Map)5 HttpUrl (okhttp3.HttpUrl)5 SharedPreferences (android.content.SharedPreferences)4 OnClick (butterknife.OnClick)4