本文整理汇总了Java中com.squareup.okhttp.Response类的典型用法代码示例。如果您正苦于以下问题:Java Response类的具体用法?Java Response怎么用?Java Response使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Response类属于com.squareup.okhttp包,在下文中一共展示了Response类的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: testWildfly
import com.squareup.okhttp.Response; //导入依赖的package包/类
/**
* Run some HTTP queries against a Docker container from image promagent/wildfly-kitchensink-promagent.
* <p/>
* The Docker container is started by the maven-docker-plugin when running <tt>mvn verify -Pwildfly</tt>.
*/
@Test
public void testWildfly() throws Exception {
OkHttpClient client = new OkHttpClient();
Request restRequest = new Request.Builder().url(System.getProperty("deployment.url") + "/rest/members").build();
// Execute REST call
Response restResponse = client.newCall(restRequest).execute();
Assertions.assertEquals(restResponse.code(), 200);
Assertions.assertTrue(restResponse.body().string().contains("John Smith"));
Thread.sleep(100); // metric is incremented after servlet has written the response, wait a little to get the updated metric
assertMetrics(client, "1.0");
// Execute REST call again
restResponse = client.newCall(restRequest).execute();
Assertions.assertEquals(restResponse.code(), 200);
Assertions.assertTrue(restResponse.body().string().contains("John Smith"));
Thread.sleep(100); // metric is incremented after servlet has written the response, wait a little to get the updated metric
assertMetrics(client, "2.0");
}
示例3: assertMetrics
import com.squareup.okhttp.Response; //导入依赖的package包/类
private void assertMetrics(OkHttpClient client, String nCalls) throws Exception {
Request metricsRequest = new Request.Builder().url(System.getProperty("promagent.url") + "/metrics").build();
Response metricsResponse = client.newCall(metricsRequest).execute();
String[] metricsLines = metricsResponse.body().string().split("\n");
String httpRequestsTotal = Arrays.stream(metricsLines)
.filter(m -> m.contains("http_requests_total"))
.filter(m -> m.contains("method=\"GET\""))
.filter(m -> m.contains("path=\"/wildfly-kitchensink/rest/members\""))
.filter(m -> m.contains("status=\"200\""))
.findFirst().orElseThrow(() -> new Exception("http_requests_total metric not found."));
assertTrue(httpRequestsTotal.endsWith(nCalls), "Value should be " + nCalls + " for " + httpRequestsTotal);
String sqlQueriesTotal = Arrays.stream(metricsLines)
.filter(m -> m.contains("sql_queries_total"))
.filter(m -> m.matches(".*?query=\"select .*?id .*?email .*?name .*?phone_number .*? from Member .*?\".*?"))
.filter(m -> m.contains("method=\"GET\""))
.filter(m -> m.contains("path=\"/wildfly-kitchensink/rest/members\""))
.findFirst().orElseThrow(() -> new Exception("sql_queries_total metric not found."));
assertTrue(sqlQueriesTotal.endsWith(nCalls), "Value should be " + nCalls + " for " + sqlQueriesTotal);
}
示例4: responseToCell
import com.squareup.okhttp.Response; //导入依赖的package包/类
private Cell responseToCell(Response response) {
try {
JSONObject jsonCell = new JSONObject(response.body().string());
Cell cell = new Cell();
cell.setLat(jsonCell.getDouble("lat"));
cell.setLon(jsonCell.getDouble("lon"));
cell.setMCC(jsonCell.getInt("mcc"));
cell.setMNC(jsonCell.getInt("mnc"));
cell.setCID(jsonCell.getInt("cellid"));
cell.setLAC(jsonCell.getInt("lac"));
return cell;
} catch (JSONException | IOException e) {
e.printStackTrace();
}
return null;
}
示例5: onOpen
import com.squareup.okhttp.Response; //导入依赖的package包/类
@Override
public void onOpen(WebSocket webSocket, Request arg1, Response arg2)
throws IOException {
mWebSocket = webSocket;
setEnvironment(WXEnvironment.getConfig());
WXSDKManager.getInstance().postOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(WXEnvironment.sApplication, "Has switched to DEBUG mode, you can see the DEBUG information on the browser!", Toast.LENGTH_SHORT).show();
}
},0);
for (JSDebuggerCallback callback : mCallbacks.values()) {
callback.onSuccess(arg2);
}
WXLogUtils.e("into--[onOpen]");
}
示例6: doInBackground
import com.squareup.okhttp.Response; //导入依赖的package包/类
/**
*
* @param params
* @return
*/
@Override
protected String doInBackground(Void... params) {
OkHttpClient client = new OkHttpClient();
HttpUrl httpUrl = HttpUrl.parse(COIN_DESK_API_URL);
//System.out.println("Requesting : " + httpUrl.toString());
FormEncodingBuilder formBody = new FormEncodingBuilder();
formBody.add("lastHours", "24");
formBody.add("maxRespArrSize", "24");
Request request = new Request.Builder()
.url(httpUrl)
.post(formBody.build())
.build();
String content = null;
try {
Response response = client.newCall(request).execute();
ResponseBody body = response.body();
if (isZipped(response)) {
content = unzip(body);
} else {
content = body.string();
}
body.close();
} catch (IOException e) {
e.printStackTrace();
}
return content;
}
示例7: get
import com.squareup.okhttp.Response; //导入依赖的package包/类
public static long get(String collection, String user) {
try {
collection = "lists." + Long.parseLong(collection);
} catch (NumberFormatException ignored) {
}
Request request = new Request.Builder()
.url(TWEETMARKER_API_URL + "?api_key=" + API_KEY + "&username=" + user + "&collection" + collection)
.get()
.build();
try {
final Response response = createHttpClientWithoutSSL().newCall(request).execute();
JSONObject json = new JSONObject(response.body().string());
return json.getJSONObject(collection).getLong("id");
} catch (IOException | JSONException | NoSuchAlgorithmException | KeyManagementException e) {
Timber.i(e, "");
}
return -1;
}
示例8: downloadNoteAsync
import com.squareup.okhttp.Response; //导入依赖的package包/类
/**
* @see #downloadNote(String)
*/
public Future<Response> downloadNoteAsync(@NonNull final String noteGuid, @Nullable EvernoteCallback<Response> callback) throws IOException {
return submitTask(new Callable<Response>() {
@Override
public Response call() throws Exception {
return downloadNote(noteGuid);
}
}, callback);
}
示例9: _getAsyn
import com.squareup.okhttp.Response; //导入依赖的package包/类
/**
* 同步的Get请求
*
* @param url
* @return Response
*/
private Response _getAsyn(String url) throws IOException {
final Request request = new Request.Builder()
.url(url)
.build();
Call call = mOkHttpClient.newCall(request);
Response execute = call.execute();
return execute;
}
示例10: getResponseJson
import com.squareup.okhttp.Response; //导入依赖的package包/类
/**
* @param client
* @param request
* @return
* @throws Exception
*/
private String getResponseJson(OkHttpClient client, Request request) throws Exception {
if (client == null || request == null) {
Log.e(TAG, "getResponseJson client == null || request == null >> return null;");
return null;
}
Response response = client.newCall(request).execute();
return response.isSuccessful() ? response.body().string() : null;
}
示例11: 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;
}
示例12: getHeaders
import com.squareup.okhttp.Response; //导入依赖的package包/类
private Headers getHeaders() throws IOException {
if (this.responseHeaders == null) {
Response response = getResponse().getResponse();
this.responseHeaders = response.headers().newBuilder().add(OkHeaders
.SELECTED_PROTOCOL, response.protocol().toString()).add(OkHeaders
.RESPONSE_SOURCE, responseSourceHeader(response)).build();
}
return this.responseHeaders;
}
示例13: 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);
}
});
}
示例14: callbackTokenError
import com.squareup.okhttp.Response; //导入依赖的package包/类
private void callbackTokenError(final BaseCallback callback, final Response response) {
mHandler.post(new Runnable() {
@Override
public void run() {
callback.onTokenError(response, response.code());
}
});
}
示例15: callbackSuccess
import com.squareup.okhttp.Response; //导入依赖的package包/类
private void callbackSuccess(final BaseCallback callback, final Response response, final Object obj) {
mHandler.post(new Runnable() {
@Override
public void run() {
callback.onSuccess(response, obj);
}
});
}