主要代码:
Request request = builder.url("http://baidu.com).get().build();
Response response = client.newCall(request).execute();
Headers requestHeaders= response.networkResponse().request().headers();
logger.info("{}", requestHeaders);
Headers responseHeaders= response.networkResponse().headers();
logger.info("{}", responseHeaders);
详细代码:
import java.util.concurrent.TimeUnit; import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import okhttp3.Cookie; import okhttp3.*; import org.junit.Assert import org.slf4j.Logger import org.slf4j.LoggerFactory public final Logger logger = TestUtils.LOGGER; public final OkHttpClient client; public final Request.Builder builder; public final Cookie.Builder cookie; Test() { client = new OkHttpClient().newBuilder() .connectTimeout(6, TimeUnit.SECONDS) .readTimeout(6, TimeUnit.SECONDS) .writeTimeout(6, TimeUnit.SECONDS) .followRedirects(false) .build(); builder = new Request.Builder(); builder.addHeader("Cache-Control", "no-cache");
builder.addHeader("Accept-Encoding", "gzip, deflate, br"); builder.addHeader("Connection", "keep-alive"); builder.addHeader("Host", "bq-color.external-st.com"); builder.addHeader("X-API-Login-Type", "1"); builder.addHeader("User-Agent", "PostmanRuntime/7.26.8"); builder.addHeader("Cookie", "xx=xx;xx=xx"); logger.info("TestRunner init..."); } @TestCase void test() { TestUtils.transactionBegin("test_tran"); Request request = builder.url("http://baidu.com").get().build(); Response response = client.newCall(request).execute(); Headers requestHeaders= response.networkResponse().request().headers();
logger.info("{}", requestHeaders);
Headers responseHeaders= response.networkResponse().headers();
logger.info("{}", responseHeaders); if(response.code() == 200){ TestUtils.transactionSuccess("test_tran"); logger.info("============= response successful, response code: {}, response body: {}",response.code(), response.body().string()); }else{ TestUtils.transactionFailure("test_tran"); logger.error("============= response false, response code: {}, response body: {}",response.code()); } response.close(); } }