Search in sources :

Example 81 with Request

use of com.squareup.okhttp.Request in project openzaly by akaxincom.

the class HttpClient method postJson.

static String postJson(String url, String json) throws IOException {
    MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    RequestBody postBody = RequestBody.create(JSON, json);
    Request request = new Request.Builder().url(url).post(postBody).build();
    Response response = client.newCall(request).execute();
    System.out.println("post postJson response =" + response.isSuccessful());
    if (response.isSuccessful()) {
        return response.body().toString();
    } else {
        System.out.println("http post failed");
        throw new IOException("post json Unexpected code " + response);
    }
}
Also used : Response(com.squareup.okhttp.Response) Request(com.squareup.okhttp.Request) MediaType(com.squareup.okhttp.MediaType) IOException(java.io.IOException) RequestBody(com.squareup.okhttp.RequestBody)

Example 82 with Request

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

the class WixelReader method readHttpJson.

// read from http source like cloud hosted parakeet receiver.cgi / json.get
private static List<TransmitterRawData> readHttpJson(String url, int numberOfRecords) {
    final List<TransmitterRawData> trd_list = new LinkedList<>();
    int processNumberOfRecords = numberOfRecords;
    // TODO make this work on preference option for the feature
    if (true)
        numberOfRecords = numberOfRecords + 1;
    long newest_timestamp = 0;
    try {
        if (httpClient == null) {
            httpClient = new OkHttpClient();
            // suitable for GPRS
            httpClient.setConnectTimeout(30, TimeUnit.SECONDS);
            httpClient.setReadTimeout(60, TimeUnit.SECONDS);
            httpClient.setWriteTimeout(20, TimeUnit.SECONDS);
        }
        // simple HTTP GET request
        // n=numberOfRecords for backfilling
        // r=sequence number to avoid any cache
        // expecting json reply like the standard json server in dexterity / python pi usb / parakeet
        final Request request = new Request.Builder().header("User-Agent", "Mozilla/5.0").header("Connection", "close").url(url + "?n=" + Integer.toString(numberOfRecords) + "&r=" + Long.toString((System.currentTimeMillis() / 1000) % 9999999)).build();
        final Response response = httpClient.newCall(request).execute();
        // if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
        if (response.isSuccessful()) {
            String[] lines = response.body().string().split("\\r?\\n");
            for (String data : lines) {
                if (data == null) {
                    Log.d(TAG, "received null continuing");
                    continue;
                }
                if (data.equals("")) {
                    Log.d(TAG, "received \"\" continuing");
                    continue;
                }
                final TransmitterRawData trd = gson.fromJson(data, TransmitterRawData.class);
                trd.CaptureDateTime = System.currentTimeMillis() - trd.RelativeTime;
                // Versions of the Python USB script after 20th May 2016 will
                // submit a bogus geolocation in the middle of the ocean to differentiate
                // themselves from actual parakeet data even though both can coexist on the
                // parakeet web service.
                // if (JoH.ratelimit("parakeet-check-notification", 9)) {
                ParakeetHelper.checkParakeetNotifications(trd.CaptureDateTime, trd.GeoLocation);
                // }
                if ((trd.GeoLocation != null)) {
                    if (!trd.GeoLocation.equals("-15,-15")) {
                        try {
                            MapsActivity.newMapLocation(trd.GeoLocation, trd.CaptureDateTime);
                        } catch (Exception e) {
                            Log.e(TAG, "Exception with maps activity: " + e.toString());
                        }
                    } else {
                        // look a little further if we see usb-wixel data on parakeet app engine
                        processNumberOfRecords = numberOfRecords + 1;
                    }
                }
                if (newest_timestamp < trd.getCaptureDateTime()) {
                    statusLog(url, JoH.hourMinuteString() + " OK data from:", trd.getCaptureDateTime());
                    newest_timestamp = trd.CaptureDateTime;
                }
                trd_list.add(0, trd);
                // System.out.println( trd.toTableString());
                if (trd_list.size() == processNumberOfRecords) {
                    // We have the data we want, let's get out
                    break;
                }
            }
            Log.i(TAG, "Success getting http json with end size: " + Integer.toString(trd_list.size()));
        }
    } catch (Exception e) {
        Log.e(TAG, "caught Exception in reading http json data " + e.toString());
    }
    return trd_list;
}
Also used : Response(com.squareup.okhttp.Response) OkHttpClient(com.squareup.okhttp.OkHttpClient) BgGraphBuilder(com.eveningoutpost.dexdrip.UtilityModels.BgGraphBuilder) Request(com.squareup.okhttp.Request) LinkedList(java.util.LinkedList) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException)

Example 83 with Request

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

the class GzipRequestInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Request originalRequest = chain.request();
    if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) {
        return chain.proceed(originalRequest);
    }
    Request compressedRequest = originalRequest.newBuilder().header("Content-Encoding", "gzip").method(originalRequest.method(), forceContentLength(gzip(originalRequest.body()))).build();
    return chain.proceed(compressedRequest);
}
Also used : Request(com.squareup.okhttp.Request)

Example 84 with Request

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

the class WebAppHelper method doInBackground.

@Override
protected Integer doInBackground(String... url) {
    try {
        Log.d(TAG, "Processing URL: " + url[0]);
        Request request = new Request.Builder().header("User-Agent", "Mozilla/5.0 (jamorham)").header("Connection", "close").url(url[0]).build();
        client.setConnectTimeout(15, TimeUnit.SECONDS);
        client.setReadTimeout(30, TimeUnit.SECONDS);
        client.setWriteTimeout(30, TimeUnit.SECONDS);
        final Response response = client.newCall(request).execute();
        if (!response.isSuccessful())
            throw new IOException("Unexpected code " + response);
        body = response.body().bytes();
    } catch (Exception e) {
        Log.d(TAG, "Exception in background task: " + e.toString());
    }
    return body.length;
}
Also used : Response(com.squareup.okhttp.Response) Request(com.squareup.okhttp.Request) IOException(java.io.IOException) IOException(java.io.IOException)

Example 85 with Request

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

the class LanguageEditor method uploadData.

private void uploadData(String data) {
    if (data.length() < 10) {
        // don't translate
        toast("No text entered - cannot send blank");
        return;
    }
    final String email = LanguageStore.getString(EMAIL_KEY);
    final String name = LanguageStore.getString(NAME_KEY);
    final String consent = LanguageStore.getString(CONSENT_KEY);
    if (email.length() == 0) {
        // don't translate
        toast("No email address stored - cannot send");
        return;
    }
    if (name.length() == 0) {
        // don't translate
        toast("No thanks name stored - cannot send");
        return;
    }
    if (consent.length() == 0) {
        // don't translate
        toast("No consent stored - cannot send");
        return;
    }
    final OkHttpClient client = new OkHttpClient();
    final String send_url = mContext.getString(R.string.wserviceurl) + "/joh-langdata";
    client.setConnectTimeout(20, TimeUnit.SECONDS);
    client.setReadTimeout(30, TimeUnit.SECONDS);
    client.setWriteTimeout(30, TimeUnit.SECONDS);
    // don't translate
    toast("Sending..");
    try {
        final RequestBody formBody = new FormEncodingBuilder().add("locale", Locale.getDefault().toString()).add("contact", email).add("name", name).add("consent", consent).add("data", data).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 language data");
                    Response response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        toast("data sent successfully");
                        ((Activity) mContext).runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                try {
                                    saveBtn.setVisibility(View.INVISIBLE);
                                    undoBtn.setVisibility(View.INVISIBLE);
                                } catch (Exception e) {
                                // do nothing if its gone away
                                }
                            }
                        });
                    } else {
                        toast("Error sending data: " + response.message());
                    }
                } catch (Exception e) {
                    Log.e(TAG, "Got exception in execute: " + e.toString());
                    // don't translate
                    toast("Error with network connection");
                }
            }
        }).start();
    } catch (Exception e) {
        toast(e.getMessage());
        Log.e(TAG, "General exception: " + e.toString());
    }
}
Also used : Response(com.squareup.okhttp.Response) OkHttpClient(com.squareup.okhttp.OkHttpClient) Request(com.squareup.okhttp.Request) FormEncodingBuilder(com.squareup.okhttp.FormEncodingBuilder) AppCompatActivity(android.support.v7.app.AppCompatActivity) Activity(android.app.Activity) RequestBody(com.squareup.okhttp.RequestBody)

Aggregations

Request (com.squareup.okhttp.Request)109 Response (com.squareup.okhttp.Response)74 IOException (java.io.IOException)61 OkHttpClient (com.squareup.okhttp.OkHttpClient)38 RequestBody (com.squareup.okhttp.RequestBody)31 FormEncodingBuilder (com.squareup.okhttp.FormEncodingBuilder)19 UnsupportedEncodingException (java.io.UnsupportedEncodingException)12 File (java.io.File)11 Callback (com.squareup.okhttp.Callback)10 InputStream (java.io.InputStream)7 Buffer (okio.Buffer)7 HttpUrl (com.squareup.okhttp.HttpUrl)5 MediaType (com.squareup.okhttp.MediaType)5 ResponseBody (com.squareup.okhttp.ResponseBody)5 SocketTimeoutException (java.net.SocketTimeoutException)5 Call (com.squareup.okhttp.Call)4 FileOutputStream (java.io.FileOutputStream)4 Activity (android.app.Activity)3 Intent (android.content.Intent)3 Uri (android.net.Uri)3