Search in sources :

Example 21 with Response

use of com.squareup.okhttp.Response in project xDrip-plus by jamorham.

the class GzipRequestInterceptor method sendFeedback.

public void sendFeedback(View myview) {
    final EditText contact = (EditText) findViewById(R.id.contactText);
    final EditText yourtext = (EditText) findViewById(R.id.yourText);
    final OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(10, TimeUnit.SECONDS);
    client.setReadTimeout(30, TimeUnit.SECONDS);
    client.setWriteTimeout(30, TimeUnit.SECONDS);
    client.interceptors().add(new GzipRequestInterceptor());
    if (yourtext.length() == 0) {
        toast("No text entered - cannot send blank");
        return;
    }
    if (contact.length() == 0) {
        toast("Without some contact info we cannot reply");
        askEmailAddress();
        return;
    }
    if (type_of_message.equals("Unknown")) {
        askType();
        return;
    }
    PersistentStore.setString(FEEDBACK_CONTACT_REFERENCE, contact.getText().toString());
    toast("Sending..");
    try {
        final RequestBody formBody = new FormEncodingBuilder().add("contact", contact.getText().toString()).add("body", JoH.getDeviceDetails() + "\n" + JoH.getVersionDetails() + "\n" + getBestCollectorHardwareName() + "\n===\n\n" + yourtext.getText().toString() + " \n\n===\nType: " + type_of_message + "\nLog data:\n\n" + log_data + "\n\n\nSent: " + JoH.dateTimeText(JoH.tsl())).add("rating", String.valueOf(myrating.getRating())).add("type", type_of_message).build();
        new Thread(new Runnable() {

            public void run() {
                try {
                    final Request request = new Request.Builder().url(send_url).post(formBody).build();
                    Log.i(TAG, "Sending feedback request");
                    final Response response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        JoH.static_toast_long(response.body().string());
                        log_data = "";
                        // Home.toaststatic("Feedback sent successfully");
                        finish();
                    } else {
                        JoH.static_toast_short("Error sending feedback: " + response.message().toString());
                    }
                } catch (Exception e) {
                    Log.e(TAG, "Got exception in execute: " + e.toString());
                    JoH.static_toast_short("Error with network connection");
                }
            }
        }).start();
    } catch (Exception e) {
        JoH.static_toast_short(e.getMessage());
        Log.e(TAG, "General exception: " + e.toString());
    }
}
Also used : EditText(android.widget.EditText) Response(com.squareup.okhttp.Response) OkHttpClient(com.squareup.okhttp.OkHttpClient) Request(com.squareup.okhttp.Request) FormEncodingBuilder(com.squareup.okhttp.FormEncodingBuilder) IOException(java.io.IOException) RequestBody(com.squareup.okhttp.RequestBody)

Example 22 with Response

use of com.squareup.okhttp.Response in project xDrip-plus by jamorham.

the class ShareRest method getOkHttpClient.

private synchronized OkHttpClient getOkHttpClient() {
    try {
        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        final OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.networkInterceptors().add(new Interceptor() {

            @Override
            public Response intercept(Chain chain) throws IOException {
                try {
                    // Add user-agent and relevant headers.
                    Request original = chain.request();
                    Request copy = original.newBuilder().build();
                    Request modifiedRequest = original.newBuilder().header("User-Agent", "CGM-Store-1.2/22 CFNetwork/711.5.6 Darwin/14.0.0").header("Content-Type", "application/json").header("Accept", "application/json").build();
                    Log.d(TAG, "Sending request: " + modifiedRequest.toString());
                    Buffer buffer = new Buffer();
                    copy.body().writeTo(buffer);
                    Log.d(TAG, "Request body: " + buffer.readUtf8());
                    final Response response = chain.proceed(modifiedRequest);
                    Log.d(TAG, "Received response: " + response.toString());
                    if (response.body() != null) {
                        MediaType contentType = response.body().contentType();
                        String bodyString = response.body().string();
                        Log.d(TAG, "Response body: " + bodyString);
                        return response.newBuilder().body(ResponseBody.create(contentType, bodyString)).build();
                    } else
                        return response;
                } catch (NullPointerException e) {
                    Log.e(TAG, "Got null pointer exception: " + e);
                    return null;
                } catch (IllegalStateException e) {
                    UserError.Log.wtf(TAG, "Got illegal state exception: " + e);
                    return null;
                }
            }
        });
        okHttpClient.setSslSocketFactory(sslSocketFactory);
        okHttpClient.setHostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        return okHttpClient;
    } catch (Exception e) {
        throw new RuntimeException("Error occurred initializing OkHttp: ", e);
    }
}
Also used : OkHttpClient(com.squareup.okhttp.OkHttpClient) MediaType(com.squareup.okhttp.MediaType) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) Interceptor(com.squareup.okhttp.Interceptor) Buffer(okio.Buffer) Request(com.squareup.okhttp.Request) SSLSession(javax.net.ssl.SSLSession) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) ExecutionException(java.util.concurrent.ExecutionException) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) HostnameVerifier(javax.net.ssl.HostnameVerifier) Response(com.squareup.okhttp.Response) X509TrustManager(javax.net.ssl.X509TrustManager)

Example 23 with Response

use of com.squareup.okhttp.Response in project ariADDna by StnetixDevTeam.

the class ApiClient method execute.

/**
 * Execute HTTP call and deserialize the HTTP response body into the given return type.
 *
 * @param returnType The return type used to deserialize HTTP response body
 * @param <T> The return type corresponding to (same with) returnType
 * @param call Call
 * @return ApiResponse object containing response status, headers and
 *   data, which is a Java object deserialized from response body and would be null
 *   when returnType is null.
 * @throws ApiException If fail to execute the call
 */
public <T> ApiResponse<T> execute(Call call, Type returnType) throws ApiException {
    try {
        Response response = call.execute();
        LOGGER.info("Method {execute} was called, with params isExecuted: {}, returnType: {}", call.isExecuted(), returnType == null ? null : returnType.getTypeName());
        T data = handleResponse(response, returnType);
        return new ApiResponse<T>(response.code(), response.headers().toMultimap(), data);
    } catch (IOException e) {
        LOGGER.error("Method {execute} was called, with params :{},{}", call.isExecuted(), returnType == null ? null : returnType.getTypeName());
        LOGGER.error("Method {execute} throw exception: " + e);
        throw new ApiException(e);
    }
}
Also used : Response(com.squareup.okhttp.Response) IOException(java.io.IOException)

Example 24 with Response

use of com.squareup.okhttp.Response in project sbt-android by scala-android.

the class DribbbleSearch method search.

@WorkerThread
public static List<Shot> search(String query, @SortOrder String sort, int page) {
    String html = null;
    // e.g https://dribbble.com/search?q=material+design&page=7&per_page=12
    HttpUrl url = new HttpUrl.Builder().scheme("https").host("dribbble.com").addPathSegment("search").addQueryParameter("q", query).addQueryParameter("s", sort).addQueryParameter("page", String.valueOf(page)).addQueryParameter("per_page", "12").build();
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder().url(url).build();
    try {
        Response response = client.newCall(request).execute();
        html = response.body().string();
    } catch (IOException ioe) {
        return null;
    }
    if (html == null)
        return null;
    Elements shotElements = Jsoup.parse(html, HOST).select("li[id^=screenshot]");
    SimpleDateFormat dateFormat = new SimpleDateFormat("MMMM d, yyyy");
    List<Shot> shots = new ArrayList<>(shotElements.size());
    for (Element element : shotElements) {
        Shot shot = parseShot(element, dateFormat);
        if (shot != null) {
            shots.add(shot);
        }
    }
    return shots;
}
Also used : OkHttpClient(com.squareup.okhttp.OkHttpClient) Element(org.jsoup.nodes.Element) Request(com.squareup.okhttp.Request) ArrayList(java.util.ArrayList) IOException(java.io.IOException) Elements(org.jsoup.select.Elements) HttpUrl(com.squareup.okhttp.HttpUrl) Response(com.squareup.okhttp.Response) SimpleDateFormat(java.text.SimpleDateFormat) Shot(io.plaidapp.data.api.dribbble.model.Shot) WorkerThread(android.support.annotation.WorkerThread)

Example 25 with Response

use of com.squareup.okhttp.Response in project pictureapp by EyeSeeTea.

the class ServerAPIController method patchClosedDate.

/**
 * Updates the orgUnit adding a closedDate
 */
static void patchClosedDate(OrganisationUnit organisationUnit) {
    String url = ServerAPIController.getServerUrl();
    try {
        String urlPathClosedDate = getPatchClosedDateUrl(url, organisationUnit.getUid());
        JSONObject data = prepareCloseDateValue(organisationUnit);
        Response response = ServerApiCallExecution.executeCall(data, urlPathClosedDate, "PATCH");
        ServerApiUtils.checkResponse(response, null);
    } catch (Exception e) {
        Log.e(TAG, String.format("patchClosedDate(%s,%s): %s", url, organisationUnit.getUid(), e.getMessage()));
    }
}
Also used : Response(com.squareup.okhttp.Response) JSONObject(org.json.JSONObject) NetworkException(org.eyeseetea.malariacare.domain.exception.NetworkException) ApiCallException(org.eyeseetea.malariacare.domain.exception.ApiCallException) ConfigJsonIOException(org.eyeseetea.malariacare.domain.exception.ConfigJsonIOException) PullConversionException(org.eyeseetea.malariacare.domain.exception.PullConversionException) JSONException(org.json.JSONException)

Aggregations

Response (com.squareup.okhttp.Response)108 Request (com.squareup.okhttp.Request)75 IOException (java.io.IOException)72 OkHttpClient (com.squareup.okhttp.OkHttpClient)33 RequestBody (com.squareup.okhttp.RequestBody)24 JSONException (org.json.JSONException)16 JSONObject (org.json.JSONObject)15 FormEncodingBuilder (com.squareup.okhttp.FormEncodingBuilder)14 UnsupportedEncodingException (java.io.UnsupportedEncodingException)10 ApiCallException (org.eyeseetea.malariacare.domain.exception.ApiCallException)10 Callback (com.squareup.okhttp.Callback)9 SocketTimeoutException (java.net.SocketTimeoutException)8 File (java.io.File)7 Buffer (okio.Buffer)7 ShowException (org.eyeseetea.malariacare.views.ShowException)7 MediaType (com.squareup.okhttp.MediaType)5 InputStream (java.io.InputStream)5 ResponseBody (com.squareup.okhttp.ResponseBody)4 ApiException (io.kubernetes.client.ApiException)4 FileOutputStream (java.io.FileOutputStream)4