本文整理汇总了Java中com.squareup.okhttp.ResponseBody类的典型用法代码示例。如果您正苦于以下问题:Java ResponseBody类的具体用法?Java ResponseBody怎么用?Java ResponseBody使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ResponseBody类属于com.squareup.okhttp包,在下文中一共展示了ResponseBody类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: doInBackground
import com.squareup.okhttp.ResponseBody; //导入依赖的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;
}
示例2: init
import com.squareup.okhttp.ResponseBody; //导入依赖的package包/类
@PostConstruct
public void init() throws IOException {
Map<String, String> headers = new HashMap<>();
String[] localVarAuthNames = new String[] { "BearerToken" };
List<Pair> queryParams = new ArrayList<>();
kc.updateParamsForAuth(localVarAuthNames, queryParams, headers);
Request.Builder builder = new Request.Builder().url(kc.getBasePath() + "/version");
for (Map.Entry<String, String> header : headers.entrySet())
builder.addHeader(header.getKey(), header.getValue());
Call call = kc.getHttpClient().newCall(builder.get().build());
ResponseBody res = call.execute().body();
Map version = om.readValue(res.byteStream(), Map.class);
String status = (String)version.get("status");
if ("Failure".equals(status))
throw new RuntimeException("/version returned " + status);
major = Integer.parseInt((String) version.get("major"));
minor = Integer.parseInt((String) version.get("minor"));
}
示例3: fromResponseBody
import com.squareup.okhttp.ResponseBody; //导入依赖的package包/类
@Override
public Converter<ResponseBody, ?> fromResponseBody(Type type, Annotation[] annotations) {
//noinspection EqualsBetweenInconvertibleTypes
if (Document.class.equals(type)) {
return new Converter<ResponseBody, Object>() {
@Override
public Object convert(ResponseBody responseBody) throws IOException {
Document doc = Jsoup.parse(responseBody.string());
responseBody.close();
return doc;
}
};
}
return null;
}
示例4: loadAndParseConfig
import com.squareup.okhttp.ResponseBody; //导入依赖的package包/类
private void loadAndParseConfig() {
Call<Config> call = ApiClient.getInstance().getApiService().getConfig();
call.enqueue(new Callback<Config>() {
@Override
public void onResponse(Response<Config> response, Retrofit retrofit) {
if (response.isSuccess()) {
Log.d("config received");
config = response.body();
getTaxonomyData();
} else {
int statusCode = response.code();
Log.d("Config data not received. Error code : " + statusCode);
ResponseBody errorBody = response.errorBody();
handleError();
}
}
@Override
public void onFailure(Throwable t) {
Log.d("config data request failed");
handleError();
}
});
}
示例5: sendPost
import com.squareup.okhttp.ResponseBody; //导入依赖的package包/类
public MPost sendPost(MPost toSend) throws IOException {
String url = host + "api/v3/teams/" + toSend.getTeamId() + "/channels/" + toSend.getChannelId()
+ "/posts/create";
String dataToSend = gson.toJson(toSend);
Request r = auth(new Request.Builder()).url(url)
.post(RequestBody.create(MediaType.parse("application/json"), dataToSend)).build();
Response response = client.newCall(r).execute();
try (ResponseBody body = response.body()) {
if (response.isSuccessful()) {
MPost msg = gson.fromJson(body.string(), MPost.class);
msg.setTeamId(toSend.getTeamId());
return msg;
}
}
return null;
}
示例6: fetchFromNetwork
import com.squareup.okhttp.ResponseBody; //导入依赖的package包/类
private ResponseBody fetchFromNetwork(Uri url, int staleness) {
Request.Builder builder = new Request.Builder();
builder.url(url.toString());
if (staleness > 0) {
builder.cacheControl(allowStaleCache(staleness));
}
Request request = builder.build();
client.setConnectTimeout(10, TimeUnit.SECONDS);
client.setReadTimeout(60, TimeUnit.SECONDS);
Log.d(TAG, "Requesting URL:" + request.urlString());
try {
Response response = client.newCall(request).execute();
if (response.cacheResponse() != null) {
Log.d(TAG, "Cached response [" + response.code() + "]:" + request.urlString());
} else {
Log.d(TAG, "Network response [" + response.code() + "]:" + request.urlString());
}
if (response.isSuccessful()) {
return response.body();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
示例7: onResponse
import com.squareup.okhttp.ResponseBody; //导入依赖的package包/类
@Override
public void onResponse(Response response) throws IOException {
if (!response.isSuccessful()) {
postOnFailure(parseUnsuccessfulResponse(response));
return;
}
ResponseBody body = response.body();
try {
Reader charStream = body.charStream();
T payload = getAdapter().fromJson(charStream);
postOnSuccess(payload);
} catch (IOException e) {
final Auth0Exception auth0Exception = new Auth0Exception("Failed to parse response to request to " + url, e);
postOnFailure(getErrorBuilder().from("Failed to parse a successful response", auth0Exception));
} finally {
closeStream(body);
}
}
示例8: getStreamFromNetwork
import com.squareup.okhttp.ResponseBody; //导入依赖的package包/类
@Override
protected InputStream getStreamFromNetwork(String imageUri, Object extra) throws IOException {
Request request = new Request.Builder().url(imageUri).build();
ResponseBody responseBody = client.newCall(request).execute().body();
InputStream inputStream = responseBody.byteStream();
int contentLength = (int) responseBody.contentLength();
return new ContentLengthInputStream(inputStream, contentLength);
}
示例9: entityFromOkHttpResponse
import com.squareup.okhttp.ResponseBody; //导入依赖的package包/类
private static HttpEntity entityFromOkHttpResponse(Response r) throws IOException {
BasicHttpEntity entity = new BasicHttpEntity();
ResponseBody body = r.body();
entity.setContent(body.byteStream());
entity.setContentLength(body.contentLength());
entity.setContentEncoding(r.header("Content-Encoding"));
if (body.contentType() != null) {
entity.setContentType(body.contentType().type());
}
return entity;
}
示例10: shouldSendGetRequest
import com.squareup.okhttp.ResponseBody; //导入依赖的package包/类
@Test
public void shouldSendGetRequest() throws ExecutionException, InterruptedException {
final Request request = new com.squareup.okhttp.Request.Builder()
.url(URI)
.method("GET", null)
.build();
when(okHttpClient.newCall(argThat(new RequestMatcher(request)))).thenReturn(call);
doAnswer(invocation -> {
final Callback callback = invocation.getArgument(0);
callback.onResponse(new Response.Builder()
.request(request)
.protocol(Protocol.HTTP_1_1)
.code(Status.OK.code())
.message("OK")
.body(ResponseBody.create(CONTENT_TYPE, "{}"))
.header("foo", "bar")
.build());
return Void.TYPE;
}).when(call).enqueue(isA(Callback.class));
final com.spotify.apollo.Response<ByteString> response =
client.send(com.spotify.apollo.Request.forUri(URI, "GET")).toCompletableFuture().get();
verify(okHttpClient, never()).setReadTimeout(anyLong(), any());
assertEquals(Optional.of(ByteString.of("{}".getBytes())), response.payload());
assertEquals(Optional.of("bar"), response.header("foo"));
}
示例11: shouldSendPostRequest
import com.squareup.okhttp.ResponseBody; //导入依赖的package包/类
@Test
public void shouldSendPostRequest() throws ExecutionException, InterruptedException {
final Request request = new com.squareup.okhttp.Request.Builder()
.url(URI)
.method("POST", RequestBody.create(CONTENT_TYPE, "{}"))
.build();
when(okHttpClient.newCall(argThat(new RequestMatcher(request)))).thenReturn(call);
doAnswer(invocation -> {
final Callback callback = invocation.getArgument(0);
callback.onResponse(new Response.Builder()
.request(request)
.protocol(Protocol.HTTP_1_1)
.code(Status.OK.code())
.message("OK")
.body(ResponseBody.create(CONTENT_TYPE, "{}"))
.header("foo", "bar")
.build());
return Void.TYPE;
}).when(call).enqueue(isA(Callback.class));
final com.spotify.apollo.Response<ByteString> response =
client.send(com.spotify.apollo.Request
.forUri(URI, "POST")
.withPayload(ByteString.of("{}".getBytes())))
.toCompletableFuture().get();
verify(okHttpClient, never()).setReadTimeout(anyLong(), any());
assertEquals(Optional.of(ByteString.of("{}".getBytes())), response.payload());
assertEquals(Optional.of("bar"), response.header("foo"));
}
示例12: unzip
import com.squareup.okhttp.ResponseBody; //导入依赖的package包/类
/**
*
* @param body
* @return
*/
private String unzip(ResponseBody body) {
try {
GzipSource responseBody = new GzipSource(body.source());
return Okio.buffer(responseBody).readUtf8();
} catch (IOException e) {
return null;
}
}
示例13: doInBackground
import com.squareup.okhttp.ResponseBody; //导入依赖的package包/类
/**
*
* @param params
* @return
*/
@Override
protected String doInBackground(Void... params) {
OkHttpClient client = new OkHttpClient();
HttpUrl httpUrl = HttpUrl.parse(TwitterSearchURL);
httpUrl = httpUrl.newBuilder()
.addQueryParameter("q", _searchTerm)
.addQueryParameter("lang", "en")
.addQueryParameter("result_type", "recent")
.build();
Request request = new Request.Builder()
.url(httpUrl)
.addHeader("Authorization", "Bearer " + _bearerToken)
.addHeader("Accept-Encoding", "gzip")
.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;
}
示例14: onMessage
import com.squareup.okhttp.ResponseBody; //导入依赖的package包/类
@Override
public void onMessage(ResponseBody body) throws IOException {
if (body.contentType() == TEXT) {
listener.textMessage(body.charStream());
} else if (body.contentType() == BINARY) {
listener.bytesMessage(body.byteStream());
}
body.close();
}
示例15: intercept
import com.squareup.okhttp.ResponseBody; //导入依赖的package包/类
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response = null;
try {
Log.i(TAG, "request is: \n" + request.toString());
Log.i(TAG, "request headers are: \n" + request.headers().toString());
Buffer buffer = new Buffer();
if (request.body() != null) {
request.body().writeTo(buffer);
}
String bodyStr = buffer.readUtf8();
Log.i(TAG, "REQUEST body is: \n" + bodyStr);
response = chain.proceed(request);
String responseBodyString = "";
MediaType type = null;
if (response.body() != null) {
type = response.body().contentType();
responseBodyString = response.body().string();
}
response = response.newBuilder().body(ResponseBody.create(type, responseBodyString.getBytes())).build();
Log.i(TAG, "RESPONSE body is \n" + responseBodyString);
return response;
} catch (Exception e) {
Log.e(TAG, "RequestInterceptor: intercept", e);
}
return response;
}