Java OkHttpClient 网络请求

Form-data请求获取Cookie中的SessionId

1.Form-data请求

public String login(String url, String name, String pwd) {
        MultipartBody body = new okhttp3.MultipartBody.Builder()
                .setType(okhttp3.MultipartBody.FORM)
                .addFormDataPart("name", name)
                .addFormDataPart("pwd", pwd).build();

        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();

        Request request = new Request.Builder()
                .url(url)
                .method("POST", body)
                .build();
        try {
            Response response = client.newCall(request).execute();
            List cookie = response.headers().values("Set-Cookie");
            String cookieContent = cookie.get(0); //eg:JSESSIONID=xxxxxxxx; Path=/; httponly; Secure; HttpOnly
            int endIndex = cookieContent.indexOf(";");
            String sessionId = cookieContent.substring(11, endIndex);
            log.info("------login sessionId={};response={}", sessionId, response);
            return putRequest("http://demo",sessionId);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

2.put请求

    public String putRequest(String url, String sessionId) {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        okhttp3.RequestBody body = okhttp3.RequestBody.create(mediaType, "{\n    \"param1\":0,\n    \"param2\":0\n}");
        Request request = new Request.Builder()
                .url(url)
                .method("PUT", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Cookie", "JSESSIONID=" + sessionId)
                .build();
        try {
            Response response = client.newCall(request).execute();
            String str = response.body().string();
            JSONObject result = JSONObject.parseObject(str);
            JSONObject data = JSONObject.parseObject(result.getString("data"));
            String dest = data.getString("url");
            log.info("------putRequest {}", str);
            return dest;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

3.另外一种form-data请求方法

private void formRequest(String url, String name, String pwd) {
        HashMap paramsMap = new HashMap<>();
        paramsMap.put("name",name);
        paramsMap.put("pwd", pwd);

        FormBody.Builder builder = new FormBody.Builder();
        for (String key : paramsMap.keySet()) {
            builder.add(key, paramsMap.get(key));
        }
        OkHttpClient okHttpClient = new OkHttpClient();
        okhttp3.RequestBody formBody = builder.build();
        Request request = new Request.Builder().url(url).post(formBody).build();
        Call call=okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                log.info("------onFailure:{}", e);
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                log.info("------onResponse:{}", string);
            }
        });
    }

你可能感兴趣的:(java,开发语言)