okhttp的项目主页https://github.com/square/okhttp 介绍页 http://square.github.io/okhttp/
使用方法以maven为例:
com.squareup.okhttp3 okhttp 3.4.1
注意:okhttp3.4.1需要jdk1.7以上版本
HttpUtil.java
package com.leegtang.demo.util; import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; public class HttpUtil { public static final MediaType JSON = MediaType .parse("application/json; charset=utf-8&ququot;); static OkHttpClient client ; static HostnameVerifier DO\_NOT\_VERIFY = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; private static SSLSocketFactory createSSLSocketFactory() { SSLSocketFactory sSLSocketFactory = null; try { SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, new TrustManager\[\]{new TrustAllManager()}, new SecureRandom()); sSLSocketFactory = sc.getSocketFactory(); } catch (Exception e) { } return sSLSocketFactory; } private static class TrustAllManager implements X509TrustManager { @Override public void checkClientTrusted(X509Certificate\[\] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate\[\] chain, String authType) throws CertificateException { } @Override public X509Certificate\[\] getAcceptedIssuers() { return new X509Certificate\[0\]; } } public static String post(String url, String json) { if(url.startsWith("https")){ // client = new OkHttpClient.Builder().sslSocketFactory(createSSLSocketFactory()).hostnameVerifier(DO_NOT_VERIFY) // .build(); client = new OkHttpClient.Builder() .sslSocketFactory(createSSLSocketFactory(),new TrustAllManager()) .hostnameVerifier(DO\_NOT\_VERIFY) .build(); }else{ client = new OkHttpClient.Builder().build(); } try { RequestBody body=null; if(json.startsWith("{")){ body= RequestBody.create(JSON, json); }else{ MediaType text=MediaType.parse("application/x-www-form-urlencoded"); body= RequestBody.create(text, json); } Request request = new Request.Builder().url(url).post(body).build(); Response response = client.newCall(request).execute(); return response.body().string(); } catch (Exception e) { e.printStackTrace(); } return null; } public static String get(String url, String json) { if(url.startsWith("https")){ client = new OkHttpClient.Builder() .sslSocketFactory(createSSLSocketFactory(),new TrustAllManager()) .hostnameVerifier(DO_NOT_VERIFY) .build(); }else{ client = new OkHttpClient.Builder().build(); } try { Request request = new Request.Builder().url(url).build(); Response response = client.newCall(request).execute(); return response.body().string(); } catch (Exception e) { e.printStackTrace(); } return null; } public static void main(String\[\] args) { String url="https://www.yf2017.top"; String json=String.format("{"loginName":"%s","pwd":"%s","serviceName":"%s"," + ""param":{"idCard":"%s","name":"%s"}" + "}","test", "123456", "IDNameCheck", "320743199101175520", "李丙付"); String res=post(url, json); System.out.println(res); } }
okhttp header
String data="_ctype_=json"; RequestBody body= RequestBody.create(MediaType.parse("application/json; charset=utf-8"), data); Request request = new Request.Builder() .url("http://www.yf2017.top/test.do?"+data) .header("Accept", "application/json, text/javascript, */*; q=0.01") // .addHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8") .post(body) .build(); OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new LoggingInterceptor()).build(); try { Response response = client.newCall(request).execute(); Stringres=response.body().string(); System.out.println(res); } catch (Exception e) { e.printStackTrace(); }
如果传入json数据,则方在RequestBody里,如果只是字符串,可以放到url后面拼接。
okhttp日志输出
package com.lcg.demo.util; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import okhttp3.Interceptor; import okhttp3.Request; import okhttp3.Response; class LoggingInterceptor implements Interceptor { Logger logger =LoggerFactory.getLogger(this.getClass()); @Override public Response intercept(Interceptor.Chain chain) throws IOException { Request request = chain.request(); long t1 = System.nanoTime(); logger.info(String.format("Sending request %s on %s%n%s", request.url(), chain.connection(), request.headers())); Response response = chain.proceed(request); long t2 = System.nanoTime(); logger.info(String.format("Received response for %s in %.1fms%n%s", response.request().url(), (t2 - t1) / 1e6d, response.headers())); return response; } } OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new LoggingInterceptor()).build();
增加logback的相关配置,可以参考
如何从log4j转到logback
(全文完)