简介:Android提供了两种HTTP通信类,HttpURLConnection和HttpClient。OKHttp是一个相对成熟的解决方案,处理了很网网络疑难杂症:会从很多常用的连接问题中自动恢复。如果服务器配置了多个IP地址,当第一个IP连接失败时,OkHttp会自动尝试下一个IP。OkHttp还处理了代理服务器问题和SSL握手失败问题。
OkHttp无需重写程序中的网络代码。OkHttp实现了几乎和java.net.HttpURLConnection一样的API。如果你用了Apache HttpClient,则OKHttp也提供了一个对应的okhttp-apache模块。
入门
官网:http://square.github.io/okhttp/
Git:https://github.com/square/okhttp
访问http
使用步骤:
android studio 添加引用
dependencies {
compile 'com.squareup.okio:okio:1.5.0'
compile 'com.squareup.okhttp3:okhttp:3.5.0'
}
get 示例
public static String sendGet(String url, String param) {
Request request = new Request.Builder().url(url + "?" + param).build();
try {
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) {
return "";
}
return response.body().string();
}
catch(Exception e){
return "";
}
}
异步get
Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call arg0, IOException arg1) {
//
}
@Override
public void onResponse(Call arg0, Response arg1) throws IOException {
//
}
});
post 示例
public static String sendPost(String url, String param,String authorization) {
FormBody.Builder formBuilder = new FormBody.Builder();
String[] array=param.split("&");
for(int i=0;i<array.length;i++){
String[] temp=array[i].split("=");
if(temp.length==2)
formBuilder.add(temp[0],temp[1]);
else
formBuilder.add(temp[0],"");
}
RequestBody body=formBuilder.build();
Request request = new Request.Builder()
.url(url)
.post(body)
.addHeader("Authorization",authorization)
.build();
try {
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) return "";
return response.body().string();
}catch(Exception e){
return "";
}
}
访问https
public static String sendPost(Context mContext,String url, String param,String authorization) {
X509TrustManager trustManager;
SSLSocketFactory sslSocketFactory;
final InputStream inputStream;
try{
inputStream = mContext.getAssets().open("test1.cer"); // 得到证书的输入流
try {
trustManager = trustManagerForCertificates(inputStream);//以流的方式读入证书
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[]{trustManager}, null);
sslSocketFactory = sslContext.getSocketFactory();
//----
FormBody.Builder formBuilder = new FormBody.Builder();
String[] array=param.split("&");
for(int i=0;i<array.length;i++){
String[] temp=array[i].split("=");
if(temp.length==2)
formBuilder.add(temp[0],temp[1]);
else
formBuilder.add(temp[0],"");
}
RequestBody body=formBuilder.build();
client=new OkHttpClient.Builder()
.sslSocketFactory(sslSocketFactory, trustManager)
.build();
Request request = new Request.Builder()
.url(url)
.post(body)
.addHeader("Authorization",authorization)
.build();
try {
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) return "";
String result=response.body().string();
return result;
}catch(Exception e){
return "";
}
//----
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}
}catch(IOException e){
return "";
}
}
private static X509TrustManager trustManagerForCertificates(InputStream in)
throws GeneralSecurityException {
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(in);
if (certificates.isEmpty()) {
throw new IllegalArgumentException("expected non-empty set of trusted certificates");
}
// Put the certificates a key store.
char[] password = "password".toCharArray(); // Any password will work.
KeyStore keyStore = newEmptyKeyStore(password);
int index = 0;
for (Certificate certificate : certificates) {
String certificateAlias = Integer.toString(index++);
keyStore.setCertificateEntry(certificateAlias, certificate);
}
// Use it to build an X509 trust manager.
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(
KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, password);
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
throw new IllegalStateException("Unexpected default trust managers:"
+ Arrays.toString(trustManagers));
}
return (X509TrustManager) trustManagers[0];
}
/**
* 添加password
* @param password
* @return
* @throws GeneralSecurityException
*/
private static KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException {
try {
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); // 这里添加自定义的密码,默认
InputStream in = null; // By convention, 'null' creates an empty key store.
keyStore.load(in, password);
return keyStore;
} catch (IOException e) {
throw new AssertionError(e);
}
}
注意事项:
如果直接引用jar包,注意引用OkHttp包后,还需要引用okio-1.11.0.jar的包才能使用。
其它网上示例:
http://blog.csdn.net/xwdoor/article/details/51063673
http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0106/2275.html