-
Notifications
You must be signed in to change notification settings - Fork 9
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
4304196
commit 7f661eb
Showing
5 changed files
with
277 additions
and
75 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
228 changes: 212 additions & 16 deletions
228
app/src/main/java/com/zongfi/zhttp/network/OkHttpStack.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,34 +1,230 @@ | ||
package com.zongfi.zhttp.network; | ||
|
||
import com.android.volley.toolbox.HurlStack; | ||
import com.android.volley.AuthFailureError; | ||
import com.android.volley.Request; | ||
import com.android.volley.toolbox.HttpStack; | ||
import com.squareup.okhttp.Call; | ||
import com.squareup.okhttp.Headers; | ||
import com.squareup.okhttp.MediaType; | ||
import com.squareup.okhttp.OkHttpClient; | ||
import com.squareup.okhttp.OkUrlFactory; | ||
import com.squareup.okhttp.Protocol; | ||
import com.squareup.okhttp.RequestBody; | ||
import com.squareup.okhttp.Response; | ||
import com.squareup.okhttp.ResponseBody; | ||
|
||
import org.apache.http.HttpEntity; | ||
import org.apache.http.HttpResponse; | ||
import org.apache.http.ProtocolVersion; | ||
import org.apache.http.StatusLine; | ||
import org.apache.http.entity.BasicHttpEntity; | ||
import org.apache.http.message.BasicHeader; | ||
import org.apache.http.message.BasicHttpResponse; | ||
import org.apache.http.message.BasicStatusLine; | ||
|
||
import java.io.IOException; | ||
import java.net.HttpURLConnection; | ||
import java.net.URL; | ||
import java.util.Map; | ||
import java.util.concurrent.TimeUnit; | ||
|
||
/** | ||
* Created by ZHZEPHI on 2015/10/20. | ||
*/ | ||
public class OkHttpStack extends HurlStack { | ||
public class OkHttpStack implements HttpStack { | ||
|
||
private final OkHttpClient client; | ||
// public OkHttpStack() { | ||
// client = new OkHttpClient(); | ||
// | ||
// //启用cookie机制 | ||
// client.setCookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER)); | ||
// | ||
// //TODO 忽略服务器验证,仅用作测试 | ||
// client.setHostnameVerifier(new HostnameVerifier() { | ||
// @Override | ||
// public boolean verify(String hostname, SSLSession session) { | ||
// return true; | ||
// } | ||
// }); | ||
// } | ||
|
||
public OkHttpStack() { | ||
this(new OkHttpClient()); | ||
} | ||
/** | ||
* 设置证书 | ||
* | ||
* @param certificates | ||
*/ | ||
// public void setCertificates(InputStream... certificates) { | ||
// try { | ||
// CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); | ||
// KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); | ||
// keyStore.load(null); | ||
// int index = 0; | ||
// for (InputStream certificate : certificates) { | ||
// String certificateAlias = Integer.toString(index++); | ||
// keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate)); | ||
// if (certificate != null) { | ||
// certificate.close(); | ||
// } | ||
// } | ||
// SSLContext sslContext = SSLContext.getInstance("TLS"); | ||
// TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); | ||
// trustManagerFactory.init(keyStore); | ||
// sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom()); | ||
// client.setSslSocketFactory(sslContext.getSocketFactory()); | ||
// } catch (CertificateException e) { | ||
// e.printStackTrace(); | ||
// } catch (KeyStoreException e) { | ||
// e.printStackTrace(); | ||
// } catch (IOException e) { | ||
// e.printStackTrace(); | ||
// } catch (NoSuchAlgorithmException e) { | ||
// e.printStackTrace(); | ||
// } catch (KeyManagementException e) { | ||
// e.printStackTrace(); | ||
// } | ||
// } | ||
|
||
private final OkHttpClient mClient; | ||
|
||
public OkHttpStack(OkHttpClient client) { | ||
if (client == null) { | ||
throw new NullPointerException("Client must not be null."); | ||
} | ||
this.client = client; | ||
this.mClient = client; | ||
} | ||
|
||
@Override | ||
protected HttpURLConnection createConnection(URL url) throws IOException { | ||
OkUrlFactory okUrlFactory = new OkUrlFactory(client); | ||
return okUrlFactory.open(url); | ||
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) | ||
throws IOException, AuthFailureError { | ||
OkHttpClient client = mClient.clone(); | ||
int timeoutMs = request.getTimeoutMs(); | ||
client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS); | ||
client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS); | ||
client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS); | ||
|
||
com.squareup.okhttp.Request.Builder okHttpRequestBuilder = | ||
new com.squareup.okhttp.Request.Builder(); | ||
okHttpRequestBuilder.url(request.getUrl()); | ||
|
||
Map<String, String> headers = request.getHeaders(); | ||
|
||
for (final String name : headers.keySet()) { | ||
okHttpRequestBuilder.addHeader(name, headers.get(name)); | ||
} | ||
|
||
for (final String name : additionalHeaders.keySet()) { | ||
okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name)); | ||
} | ||
|
||
setConnectionParametersForRequest(okHttpRequestBuilder, request); | ||
|
||
com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build(); | ||
Call okHttpCall = client.newCall(okHttpRequest); | ||
Response okHttpResponse = okHttpCall.execute(); | ||
|
||
StatusLine responseStatus = new BasicStatusLine | ||
( | ||
parseProtocol(okHttpResponse.protocol()), | ||
okHttpResponse.code(), | ||
okHttpResponse.message() | ||
); | ||
|
||
BasicHttpResponse response = new BasicHttpResponse(responseStatus); | ||
response.setEntity(entityFromOkHttpResponse(okHttpResponse)); | ||
|
||
Headers responseHeaders = okHttpResponse.headers(); | ||
|
||
for (int i = 0, len = responseHeaders.size(); i < len; i++) { | ||
final String name = responseHeaders.name(i), value = responseHeaders.value(i); | ||
|
||
if (name != null) { | ||
response.addHeader(new BasicHeader(name, value)); | ||
} | ||
} | ||
|
||
return response; | ||
} | ||
|
||
private static HttpEntity entityFromOkHttpResponse(Response response) throws IOException { | ||
BasicHttpEntity entity = new BasicHttpEntity(); | ||
ResponseBody body = response.body(); | ||
|
||
entity.setContent(body.byteStream()); | ||
entity.setContentLength(body.contentLength()); | ||
entity.setContentEncoding(response.header("Content-Encoding")); | ||
|
||
if (body.contentType() != null) { | ||
entity.setContentType(body.contentType().type()); | ||
} | ||
return entity; | ||
} | ||
|
||
@SuppressWarnings("deprecation") | ||
private static void setConnectionParametersForRequest | ||
(com.squareup.okhttp.Request.Builder builder, Request<?> request) | ||
throws IOException, AuthFailureError { | ||
switch (request.getMethod()) { | ||
case Request.Method.DEPRECATED_GET_OR_POST: | ||
// Ensure backwards compatibility. | ||
// Volley assumes a request with a null body is a GET. | ||
byte[] postBody = request.getPostBody(); | ||
|
||
if (postBody != null) { | ||
builder.post(RequestBody.create | ||
(MediaType.parse(request.getPostBodyContentType()), postBody)); | ||
} | ||
break; | ||
|
||
case Request.Method.GET: | ||
builder.get(); | ||
break; | ||
|
||
case Request.Method.DELETE: | ||
builder.delete(); | ||
break; | ||
|
||
case Request.Method.POST: | ||
builder.post(createRequestBody(request)); | ||
break; | ||
|
||
case Request.Method.PUT: | ||
builder.put(createRequestBody(request)); | ||
break; | ||
|
||
case Request.Method.HEAD: | ||
builder.head(); | ||
break; | ||
|
||
case Request.Method.OPTIONS: | ||
builder.method("OPTIONS", null); | ||
break; | ||
|
||
case Request.Method.TRACE: | ||
builder.method("TRACE", null); | ||
break; | ||
|
||
case Request.Method.PATCH: | ||
builder.patch(createRequestBody(request)); | ||
break; | ||
|
||
default: | ||
throw new IllegalStateException("Unknown method type."); | ||
} | ||
} | ||
|
||
private static ProtocolVersion parseProtocol(final Protocol protocol) { | ||
switch (protocol) { | ||
case HTTP_1_0: | ||
return new ProtocolVersion("HTTP", 1, 0); | ||
case HTTP_1_1: | ||
return new ProtocolVersion("HTTP", 1, 1); | ||
case SPDY_3: | ||
return new ProtocolVersion("SPDY", 3, 1); | ||
case HTTP_2: | ||
return new ProtocolVersion("HTTP", 2, 0); | ||
} | ||
|
||
throw new IllegalAccessError("Unkwown protocol"); | ||
} | ||
|
||
private static RequestBody createRequestBody(Request request) throws AuthFailureError { | ||
final byte[] body = request.getBody(); | ||
if (body == null) return null; | ||
|
||
return RequestBody.create(MediaType.parse(request.getBodyContentType()), body); | ||
} | ||
} |
43 changes: 0 additions & 43 deletions
43
app/src/main/java/com/zongfi/zhttp/network/SelfSignSslOkHttpStack.java
This file was deleted.
Oops, something went wrong.
Oops, something went wrong.