Search in sources :

Example 46 with MediaType

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("解析失败");
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) ByteArrayInputStream(java.io.ByteArrayInputStream) JsonElement(com.google.gson.JsonElement) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) MediaType(okhttp3.MediaType) Charset(java.nio.charset.Charset) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) JsonReader(com.google.gson.stream.JsonReader) JsonReader(com.google.gson.stream.JsonReader) IOException(java.io.IOException)

Example 47 with MediaType

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;
}
Also used : OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) MediaType(okhttp3.MediaType) RequestBody(okhttp3.RequestBody)

Example 48 with MediaType

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;
}
Also used : Buffer(okio.Buffer) HttpHeaders(okhttp3.internal.http.HttpHeaders) Headers(okhttp3.Headers) Request(okhttp3.Request) Connection(okhttp3.Connection) Charset(java.nio.charset.Charset) ResponseBody(okhttp3.ResponseBody) Response(okhttp3.Response) MediaType(okhttp3.MediaType) Protocol(okhttp3.Protocol) RequestBody(okhttp3.RequestBody) BufferedSource(okio.BufferedSource)

Example 49 with MediaType

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);
}
Also used : URL(java.net.URL) Detail(de.geeksfactory.opacclient.objects.Detail) HashMap(java.util.HashMap) Volume(de.geeksfactory.opacclient.objects.Volume) CoverHolder(de.geeksfactory.opacclient.objects.CoverHolder) TextSearchField(de.geeksfactory.opacclient.searchfields.TextSearchField) Headers(okhttp3.Headers) Filter(de.geeksfactory.opacclient.objects.Filter) CheckboxSearchField(de.geeksfactory.opacclient.searchfields.CheckboxSearchField) Part.create(okhttp3.MultipartBody.Part.create) ArrayList(java.util.ArrayList) StringProvider(de.geeksfactory.opacclient.i18n.StringProvider) RequestBody(okhttp3.RequestBody) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject) Matcher(java.util.regex.Matcher) Locale(java.util.Locale) Element(org.jsoup.nodes.Element) Map(java.util.Map) HttpClientFactory(de.geeksfactory.opacclient.networking.HttpClientFactory) Account(de.geeksfactory.opacclient.objects.Account) MediaType(okhttp3.MediaType) DateTimeFormat(org.joda.time.format.DateTimeFormat) SearchResult(de.geeksfactory.opacclient.objects.SearchResult) DateTimeFormatter(org.joda.time.format.DateTimeFormatter) MalformedURLException(java.net.MalformedURLException) BarcodeSearchField(de.geeksfactory.opacclient.searchfields.BarcodeSearchField) Set(java.util.Set) SearchRequestResult(de.geeksfactory.opacclient.objects.SearchRequestResult) IOException(java.io.IOException) SearchQuery(de.geeksfactory.opacclient.searchfields.SearchQuery) DropdownSearchField(de.geeksfactory.opacclient.searchfields.DropdownSearchField) Library(de.geeksfactory.opacclient.objects.Library) List(java.util.List) CompletableFuture(java8.util.concurrent.CompletableFuture) DetailedItem(de.geeksfactory.opacclient.objects.DetailedItem) MultipartBody(okhttp3.MultipartBody) Document(org.jsoup.nodes.Document) NotReachableException(de.geeksfactory.opacclient.networking.NotReachableException) SearchField(de.geeksfactory.opacclient.searchfields.SearchField) Jsoup(org.jsoup.Jsoup) Elements(org.jsoup.select.Elements) Pattern(java.util.regex.Pattern) AccountData(de.geeksfactory.opacclient.objects.AccountData) JSONArray(org.json.JSONArray) Copy(de.geeksfactory.opacclient.objects.Copy) FormElement(org.jsoup.nodes.FormElement) Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) Element(org.jsoup.nodes.Element) FormElement(org.jsoup.nodes.FormElement) ArrayList(java.util.ArrayList) JSONException(org.json.JSONException) SearchResult(de.geeksfactory.opacclient.objects.SearchResult) Elements(org.jsoup.select.Elements) CompletableFuture(java8.util.concurrent.CompletableFuture) SearchRequestResult(de.geeksfactory.opacclient.objects.SearchRequestResult) JSONObject(org.json.JSONObject) RequestBody(okhttp3.RequestBody)

Example 50 with MediaType

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;
}
Also used : IncomingRequestAwareClient(com.spotify.apollo.environment.IncomingRequestAwareClient) TimeUnit(java.util.concurrent.TimeUnit) Inject(javax.inject.Inject) Request(okhttp3.Request) CompletionStage(java.util.concurrent.CompletionStage) OkHttpClient(okhttp3.OkHttpClient) ByteString(okio.ByteString) Optional(java.util.Optional) CompletableFuture(java.util.concurrent.CompletableFuture) Headers(okhttp3.Headers) MediaType(okhttp3.MediaType) RequestBody(okhttp3.RequestBody) OkHttpClient(okhttp3.OkHttpClient) Headers(okhttp3.Headers) Request(okhttp3.Request) CompletableFuture(java.util.concurrent.CompletableFuture) MediaType(okhttp3.MediaType) RequestBody(okhttp3.RequestBody)

Aggregations

MediaType (okhttp3.MediaType)103 RequestBody (okhttp3.RequestBody)95 Request (okhttp3.Request)86 Response (okhttp3.Response)78 IOException (java.io.IOException)73 ResponseBody (okhttp3.ResponseBody)36 BufferedSink (okio.BufferedSink)34 Buffer (okio.Buffer)30 Charset (java.nio.charset.Charset)26 Headers (okhttp3.Headers)19 BufferedSource (okio.BufferedSource)19 Map (java.util.Map)17 OkHttpClient (okhttp3.OkHttpClient)17 InputStream (java.io.InputStream)12 HashMap (java.util.HashMap)12 MultipartBody (okhttp3.MultipartBody)12 MockResponse (okhttp3.mockwebserver.MockResponse)11 EOFException (java.io.EOFException)10 GzipSink (okio.GzipSink)10 JSONObject (org.json.JSONObject)10