use of okhttp3.MediaType in project Audient by komamj.
the class AudientResponseBodyConverter method convert.
@Override
public T convert(ResponseBody value) throws IOException {
String response = value.string();
LogUtils.i("", "convert response :" + response);
JsonElement jsonElement = jsonParser.parse(response);
String resCode = jsonElement.getAsJsonObject().get(Constants.RESPONSE_RES_CODE).getAsString();
if (TextUtils.equals(resCode, "0")) {
MediaType contentType = value.contentType();
Charset charset = contentType != null ? contentType.charset(UTF_8) : UTF_8;
InputStream inputStream = new ByteArrayInputStream(response.getBytes());
Reader reader = new InputStreamReader(inputStream, charset);
JsonReader jsonReader = gson.newJsonReader(reader);
LogUtils.i("", "------" + jsonReader.toString());
try {
return adapter.read(jsonReader);
} finally {
value.close();
}
} else {
value.close();
throw new IOException("解析失败");
}
}
use of okhttp3.MediaType in project ttdj by soonphe.
the class BCHttpClientUtil method httpPost.
/**
* http post 请求
*
* @param url 请求url
* @param jsonStr post参数
* @return BCHttpClientUtil.Response请求结果实例
*/
public static Response httpPost(String url, String jsonStr) {
Response response = new Response();
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient.Builder().connectTimeout(BCCache.getInstance().connectTimeout, TimeUnit.MILLISECONDS).build();
RequestBody body = RequestBody.create(JSON, jsonStr);
Request request = new Request.Builder().url(url).post(body).build();
proceedRequest(client, request, response);
return response;
}
use of okhttp3.MediaType in project ttdj by soonphe.
the class HttpLoggingInterceptor method intercept.
@Override
public Response intercept(Chain chain) throws IOException {
Level level = this.level;
Request request = chain.request();
if (level == Level.NONE) {
return chain.proceed(request);
}
boolean logBody = level == Level.BODY;
boolean logHeaders = logBody || level == Level.HEADERS;
RequestBody requestBody = request.body();
boolean hasRequestBody = requestBody != null;
Connection connection = chain.connection();
Protocol protocol = connection != null ? connection.protocol() : Protocol.HTTP_1_1;
String requestStartMessage = "--> " + request.method() + ' ' + request.url() + ' ' + protocol(protocol);
if (!logHeaders && hasRequestBody) {
requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
}
logger.log(requestStartMessage);
if (logHeaders) {
if (hasRequestBody) {
// them to be included (when available) so there values are known.
if (requestBody.contentType() != null) {
logger.log("Content-Type: " + requestBody.contentType());
}
if (requestBody.contentLength() != -1) {
logger.log("Content-Length: " + requestBody.contentLength());
}
}
Headers headers = request.headers();
for (int i = 0, count = headers.size(); i < count; i++) {
String name = headers.name(i);
// Skip headers from the request body as they are explicitly logged above.
if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
logger.log(name + ": " + headers.value(i));
}
}
if (!logBody || !hasRequestBody) {
logger.log("--> END " + request.method());
} else if (bodyEncoded(request.headers())) {
logger.log("--> END " + request.method() + " (encoded body omitted)");
} else {
Buffer buffer = new Buffer();
requestBody.writeTo(buffer);
Charset charset = UTF8;
MediaType contentType = requestBody.contentType();
if (contentType != null) {
charset = contentType.charset(UTF8);
}
logger.log("");
logger.log(buffer.readString(charset));
logger.log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)");
}
}
long startNs = System.nanoTime();
Response response = chain.proceed(request);
long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
ResponseBody responseBody = response.body();
long contentLength = responseBody.contentLength();
String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length";
logger.log("<-- " + response.code() + ' ' + response.message() + ' ' + response.request().url() + " (" + tookMs + "ms" + (!logHeaders ? ", " + bodySize + " body" : "") + ')');
if (logHeaders) {
Headers headers = response.headers();
for (int i = 0, count = headers.size(); i < count; i++) {
logger.log(headers.name(i) + ": " + headers.value(i));
}
if (!logBody || !HttpHeaders.hasBody(response)) {
logger.log("<-- END HTTP");
} else if (bodyEncoded(response.headers())) {
logger.log("<-- END HTTP (encoded body omitted)");
} else {
BufferedSource source = responseBody.source();
// Buffer the entire body.
source.request(Long.MAX_VALUE);
Buffer buffer = source.buffer();
Charset charset = UTF8;
MediaType contentType = responseBody.contentType();
if (contentType != null) {
charset = contentType.charset(UTF8);
}
if (contentLength != 0) {
logger.log("");
logger.log(buffer.clone().readString(charset));
}
logger.log("<-- END HTTP (" + buffer.size() + "-byte body)");
}
}
return response;
}
use of okhttp3.MediaType in project opacclient by opacapp.
the class Open method parse_search.
protected SearchRequestResult parse_search(Document doc, int page) throws OpacErrorException {
searchResultDoc = doc;
if (doc.select("#Label1, span[id$=LblInfoMessage]").size() > 0) {
String message = doc.select("#Label1, span[id$=LblInfoMessage]").text();
if (message.contains("keine Treffer")) {
return new SearchRequestResult(new ArrayList<SearchResult>(), 0, 1, page);
} else {
throw new OpacErrorException(message);
}
}
int totalCount;
if (doc.select("span[id$=TotalItemsLabel]").size() > 0) {
totalCount = Integer.parseInt(doc.select("span[id$=TotalItemsLabel]").first().text().split("[ \\t\\xA0\\u1680\\u180e\\u2000-\\u200a\\u202f\\u205f\\u3000]")[0]);
} else {
throw new OpacErrorException(stringProvider.getString(StringProvider.UNKNOWN_ERROR));
}
Pattern idPattern = Pattern.compile("\\$(mdv|civ|dcv)(\\d+)\\$");
Pattern weakIdPattern = Pattern.compile("(mdv|civ|dcv)(\\d+)[^\\d]");
Elements elements = doc.select("div[id$=divMedium], div[id$=divComprehensiveItem], div[id$=divDependentCatalogue]");
List<SearchResult> results = new ArrayList<>();
int i = 0;
List<CompletableFuture<Void>> futures = new ArrayList<>();
for (Element element : elements) {
final SearchResult result = new SearchResult();
// Cover
if (element.select("input[id$=mediumImage]").size() > 0) {
result.setCover(element.select("input[id$=mediumImage]").first().attr("src"));
} else if (element.select("img[id$=CoverView_Image]").size() > 0) {
assignBestCover(result, getCoverUrlList(element.select("img[id$=CoverView_Image]").first()));
}
Element catalogueContent = element.select(".catalogueContent, .oclc-searchmodule-mediumview-content, .oclc-searchmodule-comprehensiveitemview-content, .oclc-searchmodule-dependentitemview-content").first();
// Media Type
if (catalogueContent.select("#spanMediaGrpIcon, .spanMediaGrpIcon").size() > 0) {
String mediatype = catalogueContent.select("#spanMediaGrpIcon, .spanMediaGrpIcon").attr("class");
if (mediatype.startsWith("itemtype ")) {
mediatype = mediatype.substring("itemtype ".length());
}
SearchResult.MediaType defaulttype = defaulttypes.get(mediatype);
if (defaulttype == null)
defaulttype = SearchResult.MediaType.UNKNOWN;
if (data.has("mediatypes")) {
try {
result.setType(SearchResult.MediaType.valueOf(data.getJSONObject("mediatypes").getString(mediatype)));
} catch (JSONException e) {
result.setType(defaulttype);
}
} else {
result.setType(defaulttype);
}
} else {
result.setType(SearchResult.MediaType.UNKNOWN);
}
// Text
String title = catalogueContent.select("a[id$=LbtnShortDescriptionValue], a[id$=LbtnTitleValue]").text();
String subtitle = catalogueContent.select("span[id$=LblSubTitleValue]").text();
String author = catalogueContent.select("span[id$=LblAuthorValue]").text();
String year = catalogueContent.select("span[id$=LblProductionYearValue]").text();
String series = catalogueContent.select("span[id$=LblSeriesValue]").text();
// Some libraries, such as Bern, have labels but no <span id="..Value"> tags
int j = 0;
for (Element div : catalogueContent.children()) {
if (subtitle.equals("") && div.select("span").size() == 0 && j > 0 && j < 3) {
subtitle = div.text().trim();
}
if (author.equals("") && div.select("span[id$=LblAuthor]").size() == 1) {
author = div.text().trim();
if (author.contains(":")) {
author = author.split(":")[1];
}
}
if (year.equals("") && div.select("span[id$=LblProductionYear]").size() == 1) {
year = div.text().trim();
if (year.contains(":")) {
year = year.split(":")[1];
}
}
j++;
}
StringBuilder text = new StringBuilder();
text.append("<b>").append(title).append("</b>");
if (!subtitle.equals(""))
text.append("<br/>").append(subtitle);
if (!author.equals(""))
text.append("<br/>").append(author);
if (!year.equals(""))
text.append("<br/>").append(year);
if (!series.equals(""))
text.append("<br/>").append(series);
result.setInnerhtml(text.toString());
// ID
Matcher matcher = idPattern.matcher(element.html());
if (matcher.find()) {
result.setId(matcher.group(2));
} else {
matcher = weakIdPattern.matcher(element.html());
if (matcher.find()) {
result.setId(matcher.group(2));
}
}
// Availability
if (result.getId() != null) {
String url = opac_url + "/DesktopModules/OCLC.OPEN.PL.DNN.SearchModule/SearchService" + ".asmx/GetAvailability";
String culture = element.select("input[name$=culture]").val();
JSONObject data = new JSONObject();
try {
// Determine portalID value
int portalId = 1;
for (Element scripttag : doc.select("script")) {
String scr = scripttag.html();
if (scr.contains("LoadSharedCatalogueViewAvailabilityAsync")) {
Pattern portalIdPattern = Pattern.compile(".*LoadSharedCatalogueViewAvailabilityAsync\\([^,]*,[^,]*," + "[^0-9,]*([0-9]+)[^0-9,]*,.*\\).*");
Matcher portalIdMatcher = portalIdPattern.matcher(scr);
if (portalIdMatcher.find()) {
portalId = Integer.parseInt(portalIdMatcher.group(1));
}
}
}
data.put("portalId", portalId).put("mednr", result.getId()).put("culture", culture).put("requestCopyData", false).put("branchFilter", "");
RequestBody entity = RequestBody.create(MEDIA_TYPE_JSON, data.toString());
futures.add(asyncPost(url, entity, false).handle((response, throwable) -> {
if (throwable != null)
return null;
try {
JSONObject availabilityData = new JSONObject(response.body().string());
String isAvail = availabilityData.getJSONObject("d").getString("IsAvail");
switch(isAvail) {
case "true":
result.setStatus(SearchResult.Status.GREEN);
break;
case "false":
result.setStatus(SearchResult.Status.RED);
break;
case "digital":
result.setStatus(SearchResult.Status.UNKNOWN);
break;
}
} catch (JSONException | IOException e) {
e.printStackTrace();
}
return null;
}));
} catch (JSONException e) {
e.printStackTrace();
}
}
result.setNr(i);
results.add(result);
}
CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])).join();
return new SearchRequestResult(results, totalCount, page);
}
use of okhttp3.MediaType in project apollo by spotify.
the class HttpClient method send.
@Override
public CompletionStage<com.spotify.apollo.Response<ByteString>> send(com.spotify.apollo.Request apolloRequest, Optional<com.spotify.apollo.Request> apolloIncomingRequest) {
final Optional<RequestBody> requestBody = apolloRequest.payload().map(payload -> {
final MediaType contentType = apolloRequest.header("Content-Type").map(MediaType::parse).orElse(DEFAULT_CONTENT_TYPE);
return RequestBody.create(contentType, payload);
});
final Headers.Builder headersBuilder = new Headers.Builder();
apolloRequest.headers().asMap().forEach(headersBuilder::add);
apolloIncomingRequest.flatMap(req -> req.header(AUTHORIZATION_HEADER)).ifPresent(header -> {
if (headersBuilder.get(AUTHORIZATION_HEADER) == null) {
headersBuilder.add(AUTHORIZATION_HEADER, header);
}
});
final Request request = new Request.Builder().method(apolloRequest.method(), requestBody.orElse(null)).url(apolloRequest.uri()).headers(headersBuilder.build()).build();
final CompletableFuture<com.spotify.apollo.Response<ByteString>> result = new CompletableFuture<>();
// https://github.com/square/okhttp/wiki/Recipes#per-call-configuration
final OkHttpClient finalClient;
if (apolloRequest.ttl().isPresent() && client.readTimeoutMillis() != apolloRequest.ttl().get().toMillis()) {
finalClient = client.newBuilder().readTimeout(apolloRequest.ttl().get().toMillis(), TimeUnit.MILLISECONDS).build();
} else {
finalClient = client;
}
finalClient.newCall(request).enqueue(TransformingCallback.create(result));
return result;
}
Aggregations