Example usage for com.squareup.okhttp Response body

List of usage examples for com.squareup.okhttp Response body

Introduction

In this page you can find the example usage for com.squareup.okhttp Response body.

Prototype

ResponseBody body

To view the source code for com.squareup.okhttp Response body.

Click Source Link

Usage

From source file:com.afrisoftech.funsoft.mobilepay.MobilePayAPI.java

public static void sendProcessRequestStatus(String accessToken, String checkoutRequestID) {

    OkHttpClient client = new OkHttpClient();
    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    dateFormat.setCalendar(calendar);/*from   w  ww  . ja  v a 2  s  . com*/
    String timeStamp = dateFormat.format(calendar.getTime());
    System.out.println("Timestamp : [" + dateFormat.format(calendar.getTime()) + "]");
    String password = "174379" + "bfb279f9aa9bdbcf158e97dd71a467cd2e0c893059b10f78e6b72ada1ed2c919" + timeStamp;
    String encodedPassword = Base64.toBase64String(password.getBytes());
    ;

    System.out.println("Unencoded password : [" + password + "]");
    System.out.println("Encoded password : [" + encodedPassword + "]");
    MediaType mediaType = MediaType.parse("application/json");

    String message = null;
    JSONObject json = new JSONObject();
    try {
        json.put("BusinessShortCode", "174379");
        //json.put("Password", "MTc0Mzc5YmZiMjc5ZjlhYTliZGJjZjE1OGU5N2RkNzFhNDY3Y2QyZTBjODkzMDU5YjEwZjc4ZTZiNzJhZGExZWQyYzkxOTIwMTYwMjE2MTY1NjI3");
        json.put("Password", encodedPassword);
        //json.put("Timestamp", "20160216165627");
        json.put("Timestamp", timeStamp);
        json.put("CheckoutRequestID", checkoutRequestID);
        message = json.toString();
        System.out.println("This is the JSON String : " + message);

    } catch (JSONException ex) {
        Logger.getLogger(MobilePayAPI.class.getName()).log(Level.SEVERE, null, ex);
    }
    RequestBody body = RequestBody.create(mediaType, message);

    Request request = new Request.Builder().url("https://sandbox.safaricom.co.ke/mpesa/stkpushquery/v1/query")
            .post(body).addHeader("authorization", "Bearer " + accessToken)
            .addHeader("content-type", "application/json").build();
    try {
        Response response = client.newCall(request).execute();
        JSONObject myObject = null;
        try {
            myObject = new JSONObject(response.body().string());
        } catch (JSONException ex) {
            Logger.getLogger(MobilePayAPI.class.getName()).log(Level.SEVERE, null, ex);
        }

        System.out.println("Response for Process Request : [" + myObject.toString() + "]");

    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:com.afrisoftech.funsoft.mobilepay.MobilePayAPI.java

public static boolean registerCallbackURL(String accessToken, String shortCode, String callBackURL,
        String validationURL) {//  www.  j av a2 s  .  c  o m
    boolean checkoutRequestStatus = true;

    OkHttpClient client = new OkHttpClient();

    MediaType mediaType = MediaType.parse("application/json");

    String message = null;
    JSONObject json = new JSONObject();
    try {
        json.put("ShortCode", shortCode);
        json.put("ConfirmationURL", callBackURL);
        json.put("ValidationURL", callBackURL);
        json.put("ResponseType", "Success");
        message = json.toString();
        System.out.println("This is the JSON String : " + message);

    } catch (JSONException ex) {
        Logger.getLogger(MobilePayAPI.class.getName()).log(Level.SEVERE, null, ex);
    }
    RequestBody body = RequestBody.create(mediaType, message);
    Request request = null;
    if (com.afrisoftech.hospital.HospitalMain.mobileTxTest) {
        request = new Request.Builder().url("https://sandbox.safaricom.co.ke/mpesa/c2b/v1/registerurl") // for sandbox test cases        
                .post(body).addHeader("authorization", "Bearer " + accessToken)
                .addHeader("content-type", "application/json").build();
    } else {
        request = new Request.Builder().url("https://api.safaricom.co.ke/mpesa/c2b/v1/registerurl").post(body)
                .addHeader("authorization", "Bearer " + accessToken)
                .addHeader("content-type", "application/json").build();
    }
    try {
        Response response = client.newCall(request).execute();
        JSONObject myJsonObject = null;
        try {
            myJsonObject = new JSONObject(response.body().string());
        } catch (JSONException ex) {
            Logger.getLogger(MobilePayAPI.class.getName()).log(Level.SEVERE, null, ex);
        }

        if (myJsonObject.toString().contains("error")) {
            try {
                //                    checkoutRequestID = myJsonObject.getString("errorMessage");
                checkoutRequestStatus = false;
                System.out.println("Checkout Request ID : [" + myJsonObject.getString("errorMessage") + "]");
                javax.swing.JOptionPane.showMessageDialog(null,
                        "Payment Request Error : " + myJsonObject.getString("errorMessage") + ". Try again.");
            } catch (JSONException ex) {
                ex.printStackTrace();
            }
        } else if (myJsonObject.toString().contains("Success")) {
            try {
                checkoutRequestStatus = true;

                System.out
                        .println("Checout Request ID : [" + myJsonObject.getString("CheckoutRequestID") + "]");

            } catch (JSONException ex) {
                ex.printStackTrace();
            }
        }
        System.out.println("Response for Process Request : [" + myJsonObject.toString() + "]");

    } catch (IOException ex) {
        ex.printStackTrace();
    }

    return checkoutRequestStatus;
}

From source file:com.aix.city.comm.OkHttpStack.java

License:Open Source License

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());
    }/*from  w ww . j  a  v a  2 s .co  m*/
    return entity;
}

From source file:com.andrew67.ddrfinder.adapters.MapLoaderV1.java

License:Open Source License

@Override
protected ApiResult doInBackground(LatLngBounds... boxes) {
    // Fetch machine data in JSON format
    JSONArray jArray = new JSONArray();
    try {/*from   w ww . ja  v a  2s . co  m*/
        if (boxes.length == 0)
            throw new IllegalArgumentException("No boxes passed to doInBackground");
        final LatLngBounds box = boxes[0];

        final OkHttpClient client = new OkHttpClient();
        final String LOADER_API_URL = sharedPref.getString(SettingsActivity.KEY_PREF_API_URL, "");
        final HttpUrl requestURL = HttpUrl.parse(LOADER_API_URL).newBuilder()
                .addQueryParameter("source", "android")
                .addQueryParameter("latupper", "" + box.northeast.latitude)
                .addQueryParameter("longupper", "" + box.northeast.longitude)
                .addQueryParameter("latlower", "" + box.southwest.latitude)
                .addQueryParameter("longlower", "" + box.southwest.longitude).build();

        Log.d("api", "Request URL: " + requestURL);
        final Request get = new Request.Builder().header("User-Agent", BuildConfig.APPLICATION_ID + " "
                + BuildConfig.VERSION_NAME + "/Android?SDK=" + Build.VERSION.SDK_INT).url(requestURL).build();

        final Response response = client.newCall(get).execute();
        final int statusCode = response.code();
        Log.d("api", "Status code: " + statusCode);

        // Data loaded OK
        if (statusCode == 200) {
            final String jResponse = response.body().string();
            Log.d("api", "Raw API result: " + jResponse);
            jArray = new JSONArray(jResponse);
        }
        // Code used for invalid parameters; in this case exceeding
        // the limits of the boundary box
        else if (statusCode == 400) {
            return new ApiResultV1(ApiResultV1.ERROR_ZOOM);
        }
        // Unexpected error code
        else {
            return new ApiResultV1(ApiResultV1.ERROR_API);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    // Return list
    ArrayList<ArcadeLocation> out = new ArrayList<>();
    try {
        for (int i = 0; i < jArray.length(); ++i) {
            final JSONObject obj = (JSONObject) jArray.get(i);
            final String name = obj.getString("name");

            boolean closed = false;
            if (ArcadeLocation.CLOSED.matcher(name).matches()) {
                closed = true;
            }
            // Fields added after ddr-finder 1.0 API should be
            // explicitly tested for, in order to maintain
            // compatibility with deployments of older versions
            boolean hasDDR = false;
            if (obj.has("hasDDR") && obj.getInt("hasDDR") == 1) {
                hasDDR = true;
            }

            out.add(new ArcadeLocationV1(obj.getInt("id"), name, obj.getString("city"),
                    new LatLng(obj.getDouble("latitude"), obj.getDouble("longitude")), hasDDR, closed));
        }
    } catch (Exception e) {
        out.clear();
    }
    return new ApiResultV1(out, boxes[0]);
}

From source file:com.andrew67.ddrfinder.adapters.MapLoaderV3.java

License:Open Source License

@Override
protected ApiResult doInBackground(LatLngBounds... boxes) {
    ApiResult result = null;/*from   w  w w. j a  v a2  s  . c  o m*/
    try {
        if (boxes.length == 0)
            throw new IllegalArgumentException("No boxes passed to doInBackground");
        final LatLngBounds box = boxes[0];

        String datasrc = sharedPref.getString(SettingsActivity.KEY_PREF_API_SRC, "");
        if (SettingsActivity.API_SRC_CUSTOM.equals(datasrc)) {
            datasrc = sharedPref.getString(SettingsActivity.KEY_PREF_API_SRC_CUSTOM, "");
        }

        final OkHttpClient client = new OkHttpClient();
        final String LOADER_API_URL = sharedPref.getString(SettingsActivity.KEY_PREF_API_URL, "");
        final HttpUrl requestURL = HttpUrl.parse(LOADER_API_URL).newBuilder()
                .addQueryParameter("version", "" + SettingsActivity.API_V30)
                .addQueryParameter("datasrc", datasrc)
                .addQueryParameter("latupper", "" + box.northeast.latitude)
                .addQueryParameter("lngupper", "" + box.northeast.longitude)
                .addQueryParameter("latlower", "" + box.southwest.latitude)
                .addQueryParameter("lnglower", "" + box.southwest.longitude).build();

        Log.d("api", "Request URL: " + requestURL);
        final Request get = new Request.Builder().header("User-Agent", BuildConfig.APPLICATION_ID + " "
                + BuildConfig.VERSION_NAME + "/Android?SDK=" + Build.VERSION.SDK_INT).url(requestURL).build();

        final Response response = client.newCall(get).execute();
        final int statusCode = response.code();
        Log.d("api", "Status code: " + statusCode);

        // Data/error loaded OK
        if (statusCode == 200 || statusCode == 400) {
            final Gson gson = new Gson();
            result = gson.fromJson(response.body().charStream(), Result.class);
            result.setBounds(box);
            Log.d("api", "Raw API result: " + gson.toJson(result, Result.class));
        }
        // Unexpected error code
        else {
            throw new RuntimeException("Unexpected HTTP status code: " + statusCode);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}

From source file:com.android.cloudfiles.cloudfilesforandroid.CloudFiles.java

License:Apache License

public Response download(String region, String bucket, String key, String target) throws IOException {

    String string = getObjectCdnUrl(region, bucket, key);

    Request request = new Request.Builder().url(string)

            .get().build();/*from www .j  a v a 2 s  . c om*/

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful())
        throw new IOException("Unexpected code " + response);

    FileOutputStream f = new FileOutputStream(target);
    BufferedSink sink = Okio.buffer(Okio.sink(f));
    sink.write(response.body().bytes());
    sink.close();

    return response;

}

From source file:com.android.cloudfiles.cloudfilesforandroid.CloudFiles.java

License:Apache License

private String generateToken(String userName, String apiKey) throws IOException {

    JsonObject cred = new JsonObject();
    cred.addProperty("username", userName);
    cred.addProperty("apiKey", apiKey);
    JsonObject rax = new JsonObject();
    rax.add("RAX-KSKEY:apiKeyCredentials", cred);

    JsonObject obj = new JsonObject();
    obj.add("auth", rax);
    String json = obj.toString();

    RequestBody body = RequestBody.create(JSON, json);
    Request request = new Request.Builder().url(tokenURL).post(body).build();
    Response response = client.newCall(request).execute();

    if (!response.isSuccessful())
        throw new IOException("Unexpected code " + response);

    return response.body().string();
}

From source file:com.android.codg.rentadeactivos.TestWebServer.java

public String getString1(String metodo, RequestBody formBody) {

    try {//from   w  w  w.  j  ava  2s  .  c o m
        URL url = new URL("http://192.168.0.16:5000/" + metodo);
        Request request = new Request.Builder().url(url).post(formBody).build();
        Response response = webClient.newCall(request).execute();//Aqui obtiene la respuesta en dado caso si hayas pues un return en python
        String response_string = response.body().string();//y este seria el string de las respuesta
        //System.out.println(response_string);
        return response_string;
    } catch (MalformedURLException ex) {
        return "aldo";
    } catch (Exception ex) {
        String mensaje = ex.toString();
        return mensaje;
    }
}

From source file:com.android.ted.gank.service.ImageImproveService.java

License:Apache License

/***
 * ?/*from   ww  w  . java 2  s.c o m*/
 * @param url
 * @param measured
 * @throws IOException
 */
public void loadImageForSize(String url, Point measured) throws IOException {
    Response response = client.newCall(new Request.Builder().url(url).build()).execute();
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(response.body().byteStream(), null, options);
    measured.x = options.outWidth;
    measured.y = options.outHeight;
}

From source file:com.androidso.lib.net.http.OkHttpStack.java

License:Open Source License

private static HttpEntity entityFromOkHttpResponse(Response r) throws IOException {
    BasicHttpEntity entity = new BasicHttpEntity() {
        @Override/*from  ww w.j  a va  2  s . c o m*/
        public void consumeContent() {
            //                getContent().close();

        }
    };
    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;
}