本文整理匯總了Java中com.squareup.okhttp.Response.code方法的典型用法代碼示例。如果您正苦於以下問題:Java Response.code方法的具體用法?Java Response.code怎麽用?Java Response.code使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類com.squareup.okhttp.Response
的用法示例。
在下文中一共展示了Response.code方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: handleResponse
import com.squareup.okhttp.Response; //導入方法依賴的package包/類
/**
* Handle the given response, return the deserialized object when the response is successful.
*
* @param <T> Type
* @param response Response
* @param returnType Return type
* @throws ApiException If the response has a unsuccessful status code or
* fail to deserialize the response body
* @return Type
*/
public <T> T handleResponse(Response response, Type returnType) throws ApiException {
if (response.isSuccessful()) {
if (returnType == null || response.code() == 204) {
// returning null if the returnType is not defined,
// or the status code is 204 (No Content)
return null;
} else {
return deserialize(response, returnType);
}
} else {
String respBody = null;
if (response.body() != null) {
try {
respBody = response.body().string();
} catch (IOException e) {
throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap());
}
}
throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody);
}
}
示例2: handleMessage
import com.squareup.okhttp.Response; //導入方法依賴的package包/類
@Override
public void handleMessage(Message msg) {
int what = msg.what;
switch (what) {
case SUBMIT: {
WXHttpTask task = (WXHttpTask) msg.obj;
Request.Builder builder = new Request.Builder().header("User-Agent", "WeAppPlusPlayground/1.0").url(task.url);
WXHttpResponse httpResponse = new WXHttpResponse();
try {
Response response = mOkHttpClient.newCall(builder.build()).execute();
httpResponse.code = response.code();
httpResponse.data = response.body().bytes();
task.response = httpResponse;
mUiHandler.sendMessage(mUiHandler.obtainMessage(1, task));
} catch (Throwable e) {
e.printStackTrace();
httpResponse.code = 1000;
mUiHandler.sendMessage(mUiHandler.obtainMessage(1, task));
}
}
break;
default:
break;
}
}
示例3: parseBody
import com.squareup.okhttp.Response; //導入方法依賴的package包/類
/**
* @param response The returned server response.
* @return The note content if the server returned {@code 200} as status code, otherwise {@code null}.
* @throws IOException
*/
public String parseBody(@NonNull Response response) throws IOException {
if (response.code() == 200) {
return response.body().string();
} else {
return null;
}
}
示例4: processAuthHeader
import com.squareup.okhttp.Response; //導入方法依賴的package包/類
public static Request processAuthHeader(Authenticator authenticator, Response response, Proxy
proxy) throws IOException {
if (response.code() == 407) {
return authenticator.authenticateProxy(proxy, response);
}
return authenticator.authenticate(proxy, response);
}
示例5: isCacheable
import com.squareup.okhttp.Response; //導入方法依賴的package包/類
public static boolean isCacheable(Response response, Request request) {
switch (response.code()) {
case 200:
case 203:
case 204:
case 300:
case SampleTinkerReport.KEY_LOADED_MISMATCH_LIB /*301*/:
case 308:
case SampleTinkerReport.KEY_LOADED_SUCC_COST_OTHER /*404*/:
case 405:
case 410:
case 414:
case 501:
break;
case SampleTinkerReport.KEY_LOADED_MISMATCH_RESOURCE /*302*/:
case 307:
if (response.header("Expires") == null && response.cacheControl().maxAgeSeconds()
== -1 && !response.cacheControl().isPublic() && !response.cacheControl()
.isPrivate()) {
return false;
}
default:
return false;
}
return (response.cacheControl().noStore() || request.cacheControl().noStore()) ? false :
true;
}
示例6: hasBody
import com.squareup.okhttp.Response; //導入方法依賴的package包/類
public static boolean hasBody(Response response) {
if (response.request().method().equals(HTTP.HEAD)) {
return false;
}
int responseCode = response.code();
if ((responseCode < 100 || responseCode >= 200) && responseCode != 204 && responseCode !=
SampleTinkerReport.KEY_LOADED_MISSING_LIB) {
return true;
}
if (OkHeaders.contentLength(response) != -1 || "chunked".equalsIgnoreCase(response.header
("Transfer-Encoding"))) {
return true;
}
return false;
}
示例7: validate
import com.squareup.okhttp.Response; //導入方法依賴的package包/類
private static boolean validate(Response cached, Response network) {
if (network.code() == SampleTinkerReport.KEY_LOADED_MISSING_LIB) {
return true;
}
Date lastModified = cached.headers().getDate("Last-Modified");
if (lastModified != null) {
Date networkLastModified = network.headers().getDate("Last-Modified");
if (networkLastModified != null && networkLastModified.getTime() < lastModified
.getTime()) {
return true;
}
}
return false;
}
示例8: responseSourceHeader
import com.squareup.okhttp.Response; //導入方法依賴的package包/類
private static String responseSourceHeader(Response response) {
if (response.networkResponse() == null) {
if (response.cacheResponse() == null) {
return "NONE";
}
return "CACHE " + response.code();
} else if (response.cacheResponse() == null) {
return "NETWORK " + response.code();
} else {
return "CONDITIONAL_CACHE " + response.networkResponse().code();
}
}
示例9: createTunnel
import com.squareup.okhttp.Response; //導入方法依賴的package包/類
private void createTunnel(int readTimeout, int writeTimeout) throws IOException {
Request tunnelRequest = createTunnelRequest();
HttpUrl url = tunnelRequest.httpUrl();
String requestLine = "CONNECT " + url.host() + ":" + url.port() + " HTTP/1.1";
do {
Http1xStream tunnelConnection = new Http1xStream(null, this.source, this.sink);
this.source.timeout().timeout((long) readTimeout, TimeUnit.MILLISECONDS);
this.sink.timeout().timeout((long) writeTimeout, TimeUnit.MILLISECONDS);
tunnelConnection.writeRequest(tunnelRequest.headers(), requestLine);
tunnelConnection.finishRequest();
Response response = tunnelConnection.readResponse().request(tunnelRequest).build();
long contentLength = OkHeaders.contentLength(response);
if (contentLength == -1) {
contentLength = 0;
}
Source body = tunnelConnection.newFixedLengthSource(contentLength);
Util.skipAll(body, ActivityChooserViewAdapter.MAX_ACTIVITY_COUNT_UNLIMITED, TimeUnit
.MILLISECONDS);
body.close();
switch (response.code()) {
case 200:
if (!this.source.buffer().exhausted() || !this.sink.buffer().exhausted()) {
throw new IOException("TLS tunnel buffered too many bytes!");
}
return;
case 407:
tunnelRequest = OkHeaders.processAuthHeader(this.route.getAddress()
.getAuthenticator(), response, this.route.getProxy());
break;
default:
throw new IOException("Unexpected response code for CONNECT: " + response
.code());
}
} while (tunnelRequest != null);
throw new IOException("Failed to authenticate with proxy");
}
示例10: onRet
import com.squareup.okhttp.Response; //導入方法依賴的package包/類
private void onRet(Response response, String ip, long duration, CompletionHandler complete) {
int code = response.code();
String reqId = response.header("X-Reqid");
reqId = reqId == null ? null : reqId.trim();
byte[] body = null;
String error = null;
try {
body = response.body().bytes();
} catch (IOException e) {
error = e.getMessage();
}
JSONObject json = null;
if (!ctype(response).equals("application/json") || body == null) {
String str = new String(body);
} else {
try {
json = buildJsonResp(body);
if (response.code() != 200) {
error = json.optString("error", new String(body, Constants.UTF_8));
}
} catch (Exception e2) {
if (response.code() < 300) {
error = e2.getMessage();
}
}
}
URL u = response.request().url();
final ResponseInfo info = new ResponseInfo(code, reqId, response.header("X-Log"), via
(response), u.getHost(), u.getPath(), ip, u.getPort(), (double) duration, 0, error);
final CompletionHandler completionHandler = complete;
final JSONObject jSONObject = json;
AsyncRun.run(new Runnable() {
public void run() {
completionHandler.complete(info, jSONObject);
}
});
}
示例11: requestNewToken
import com.squareup.okhttp.Response; //導入方法依賴的package包/類
private void requestNewToken(String grantType) throws IOException {
Map<String, String> localVarHeaderParams = new HashMap<>();
localVarHeaderParams.put("Accept", "application/json");
String method = "GET";
String[] localVarAuthNames = new String[] {};
List<Pair> localVarQueryParams = new ArrayList<>();
Map<String, Object> formParams = new HashMap<>();
localVarQueryParams.addAll(apiClient.parameterToPairs("", "grant_type", grantType));
if ("refresh_token".equals(grantType) || "password".equals(grantType)) {
String client = authenticationProperties.get(KEY_CLIENT);
String secret = authenticationProperties.get(KEY_SECRET);
byte[] creds = (client + ":" + secret).getBytes();
localVarHeaderParams.put("Authorization", "Basic " + Base64.getEncoder().encodeToString(creds));
}
if ("refresh_token".equals(grantType)) {
localVarQueryParams.addAll(apiClient.parameterToPairs("", "refresh_token", currentToken.getRefreshToken()));
}
if ("password".equals(grantType)) {
localVarHeaderParams.put("Content-Type", "multipart/form-data");
method = "POST";
formParams.put("username", authenticationProperties.get(KEY_USERNAME));
formParams.put("password", authenticationProperties.get(KEY_PASSWORD));
}
Response response = null;
try {
Request r = apiClient.buildRequest("/oauth/token", method, localVarQueryParams, null, localVarHeaderParams, formParams, localVarAuthNames, null);
logger.debug(r.toString());
Call call = apiClient.buildCall(r);
response = call.execute();
if (response.isSuccessful()) {
MyOAuthToken newToken = apiClient.deserialize(response, myOAuthTokenType);
newToken.computeExpirationDate();
currentToken = newToken;
} else {
throw new IOException("Unable to get an authentication token (" + response.code() + ") : Msg(" + response.message() + ") Body("
+ (response.body() != null ? response.body().string() : "") + ")");
}
} catch (ApiException e) {
throw new IOException(e);
} finally {
if (response != null) {
response.body().close();
}
}
}
示例12: requestNewOCIDKey
import com.squareup.okhttp.Response; //導入方法依賴的package包/類
/**
*
* Get an API key for Open Cell ID. Do not call this from the UI/Main thread.
* For the various server responses, pleas refer to the OpenCellID API wiki:
* See: http://wiki.opencellid.org/wiki/API#Error_codes
*
* OCID status codes http://wiki.opencellid.org/wiki/API#Error_codes
*
* 1 200 Cell not found
* 2 401 Invalid API key
* 3 400 Invalid input data
* 4 403 Your API key must be white listed in order to run this operation
* 5 500 Internal server error
* 6 503 Too many requests. Try later again
* 7 429 Daily limit 1000 requests exceeded for your API key.
*
* @return null or newly generated key
*/
public String requestNewOCIDKey() throws IOException {
Request request = new Request.Builder()
.get()
.url(getString(R.string.opencellid_api_get_key))
.build();
Response response = okHttpClient.newCall(request).execute();
int responseCode = response.code();
String htmlResponse = response.body().string();
// For debugging HTTP server response and codes
Log.d(TAG, mTAG + "Response Html=" + htmlResponse + " Response Code=" + String.valueOf(responseCode));
if (responseCode == 200) {
Log.d(TAG, mTAG + "OCID Code 1: Cell Not found: " + htmlResponse);
return htmlResponse;
} else if (responseCode == 401) {
Log.d(TAG, mTAG + "OCID Code 2: Invalid API Key! :" + htmlResponse);
return htmlResponse;
} else if (responseCode == 400) {
Log.d(TAG, mTAG + "OCID Code 3: Invalid input data: " + htmlResponse);
return "Bad Request"; // For making a toast!
} else if (responseCode == 403) {
Log.d(TAG, mTAG + "OCID Code 4: Your API key must be white listed: " + htmlResponse);
return "Bad Request"; // For making a toast!
} else if (responseCode == 500) {
Log.d(TAG, mTAG + "OCID Code 5: Remote internal server error: " + htmlResponse);
return "Bad Request"; // For making a toast!
} else if (responseCode == 503) {
Log.d(TAG, mTAG + "OCID Code 6: Reached 24hr API key request limit: " + htmlResponse);
return htmlResponse;
} else if (responseCode == 429) {
Log.d(TAG, mTAG + "OCID Code 7: Exceeded daily request limit (1000) for your API key: " + htmlResponse);
return htmlResponse;
} else {
Log.d(TAG, mTAG + "OCID Returned Unknown Response: " + responseCode);
return null;
}
}
示例13: flush
import com.squareup.okhttp.Response; //導入方法依賴的package包/類
@Override
public void flush() throws TTransportException {
Util.closeQuietly(mResponseBody);
mResponseBody = null;
RequestBody requestBody = new RequestBody() {
@Override
public MediaType contentType() {
if (mHeaders != null && mHeaders.containsKey("Content-Type")) {
return MediaType.parse(mHeaders.get("Content-Type"));
} else {
return MEDIA_TYPE_THRIFT;
}
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
sink.write(mByteStore.getData(), 0, mByteStore.getBytesWritten());
}
};
try {
Request.Builder builder = new Request.Builder()
.url(mUrl)
.post(requestBody);
if (mHeaders != null) {
for (String name : mHeaders.keySet()) {
builder.header(name, mHeaders.get(name));
}
}
Response response = mHttpClient.newCall(builder.build()).execute();
if (response.code() != 200) {
throw new TTransportException("HTTP Response code: " + response.code() + ", message " + response.message());
}
mResponseBody = response.body().byteStream();
} catch (Exception e) {
throw new TTransportException(e);
} finally {
try {
mByteStore.reset();
} catch (IOException ignored) {
}
}
}
示例14: get
import com.squareup.okhttp.Response; //導入方法依賴的package包/類
public static StatusLine get(Response response) {
return new StatusLine(response.protocol(), response.code(), response.message());
}
示例15: proceed
import com.squareup.okhttp.Response; //導入方法依賴的package包/類
public Response proceed(Request request) throws IOException {
this.calls++;
if (this.index > 0) {
Interceptor caller = (Interceptor) this.this$0.client.networkInterceptors().get(this
.index - 1);
Address address = connection().getRoute().getAddress();
if (!request.httpUrl().host().equals(address.getUriHost()) || request.httpUrl().port
() != address.getUriPort()) {
throw new IllegalStateException("network interceptor " + caller + " must retain " +
"the same host and port");
} else if (this.calls > 1) {
throw new IllegalStateException("network interceptor " + caller + " must call " +
"proceed() exactly once");
}
}
if (this.index < this.this$0.client.networkInterceptors().size()) {
HttpEngine$NetworkInterceptorChain chain = new HttpEngine$NetworkInterceptorChain
(this.this$0, this.index + 1, request);
Interceptor interceptor = (Interceptor) this.this$0.client.networkInterceptors().get
(this.index);
Response intercept = interceptor.intercept(chain);
if (chain.calls != 1) {
throw new IllegalStateException("network interceptor " + interceptor + " must " +
"call proceed() exactly once");
} else if (intercept != null) {
return intercept;
} else {
throw new NullPointerException("network interceptor " + interceptor + " returned " +
"null");
}
}
HttpEngine.access$000(this.this$0).writeRequestHeaders(request);
HttpEngine.access$102(this.this$0, request);
if (this.this$0.permitsRequestBody(request) && request.body() != null) {
BufferedSink bufferedRequestBody = Okio.buffer(HttpEngine.access$000(this.this$0)
.createRequestBody(request, request.body().contentLength()));
request.body().writeTo(bufferedRequestBody);
bufferedRequestBody.close();
}
Response response = HttpEngine.access$200(this.this$0);
int code = response.code();
if ((code != 204 && code != 205) || response.body().contentLength() <= 0) {
return response;
}
throw new ProtocolException("HTTP " + code + " had non-zero Content-Length: " + response.body().contentLength());
}