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:co.waitlisted.api.SiteApi.java

License:Apache License

private com.squareup.okhttp.Call getSiteCall(final ProgressResponseBody.ProgressListener progressListener,
        final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
    Object wllocalVarPostBody = null;

    // create path and map variables
    String wllocalVarPath = "/site".replaceAll("\\{format\\}", "json");

    List<Pair> wllocalVarQueryParams = new ArrayList<Pair>();

    Map<String, String> wllocalVarHeaderParams = new HashMap<String, String>();

    Map<String, Object> wllocalVarFormParams = new HashMap<String, Object>();

    final String[] wllocalVarAccepts = { "application/json" };
    final String wllocalVarAccept = wlapiClient.selectHeaderAccept(wllocalVarAccepts);
    if (wllocalVarAccept != null)
        wllocalVarHeaderParams.put("Accept", wllocalVarAccept);

    final String[] wllocalVarContentTypes = { "application/json" };
    final String wllocalVarContentType = wlapiClient.selectHeaderContentType(wllocalVarContentTypes);
    wllocalVarHeaderParams.put("Content-Type", wllocalVarContentType);

    if (progressListener != null) {
        apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
            @Override/* w  w  w.  j a  v a 2  s.co m*/
            public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain)
                    throws IOException {
                com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
                return originalResponse.newBuilder()
                        .body(new ProgressResponseBody(originalResponse.body(), progressListener)).build();
            }
        });
    }

    String[] wllocalVarAuthNames = new String[] {};
    return wlapiClient.buildCall(wllocalVarPath, "GET", wllocalVarQueryParams, wllocalVarPostBody,
            wllocalVarHeaderParams, wllocalVarFormParams, wllocalVarAuthNames, progressRequestListener);
}

From source file:com.abiquo.apiclient.RestClient.java

License:Apache License

private <T> T execute(final Request request, final Class<T> resultClass) throws IOException {
    logRequest(request);/*w  w  w. ja va2 s . c o m*/

    Response response = client.newCall(request).execute();
    String responseBody = response.body().string();

    logResponse(response, responseBody);
    checkResponse(request, response, responseBody);

    return !Strings.isNullOrEmpty(responseBody) && resultClass != null ? json.read(responseBody, resultClass)
            : null;
}

From source file:com.abiquo.apiclient.RestClient.java

License:Apache License

private <T> T execute(final Request request, final TypeToken<T> returnType) throws IOException {
    logRequest(request);//w ww .  ja  v  a  2 s.  com

    Response response = client.newCall(request).execute();
    String responseBody = response.body().string();

    logResponse(response, responseBody);
    checkResponse(request, response, responseBody);

    return !Strings.isNullOrEmpty(responseBody) && returnType != null ? json.read(responseBody, returnType)
            : null;
}

From source file:com.ae.apps.pnrstatus.service.NetworkService.java

License:Open Source License

public String doGetRequest(final String httpUrl, List<Pair<String, String>> params) throws Exception {
    HttpUrl.Builder urlBuilder = HttpUrl.parse(httpUrl).newBuilder();

    // Add Query Params if present
    if (null != params && !params.isEmpty()) {
        for (Pair<String, String> param : params) {
            urlBuilder.addQueryParameter(param.first, param.second);
        }//from ww w .  ja  v a 2 s.c o m
    }

    String url = urlBuilder.build().toString();

    try {
        Request request = new Request.Builder().url(url).build();
        Response response = client.newCall(request).execute();

        return response.body().string();
    } catch (IOException ex) {
        throw new StatusException(ex.getMessage(), StatusException.ErrorCodes.URL_ERROR);
    }
}

From source file:com.ae.apps.pnrstatus.service.NetworkService.java

License:Open Source License

public String doPostRequest(final String targetUrl, final Map<String, String> headers,
        final Map<String, String> params) throws StatusException {
    //RequestBody requestBody = RequestBody.create(WEB_FORM, "");
    try {//from  www.j  a v  a  2  s.  com
        Request.Builder requestBuilder = new Request.Builder().url(targetUrl);
        if (null != headers) {
            for (String key : headers.keySet()) {
                requestBuilder.addHeader(key, String.valueOf(headers.get(key)));
            }
        }
        //--
        FormEncodingBuilder formEncodingBuilder = new FormEncodingBuilder();
        if (null != params) {
            for (String key : params.keySet()) {
                formEncodingBuilder.add(key, String.valueOf(params.get(key)));
            }
        }

        RequestBody formBody = formEncodingBuilder.build();
        Request request = requestBuilder.url(targetUrl).post(formBody).build();

        Response response = client.newCall(request).execute();
        return response.body().string();
    } catch (IOException ex) {
        throw new StatusException(ex.getMessage(), StatusException.ErrorCodes.URL_ERROR);
    }
}

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

public static String encodetoBase64String(String stringtoEncode) {

    String appKeySecret = com.afrisoftech.hospital.HospitalMain.oAuthKey;
    //    String appKeySecret = app_key + ":" + app_secret;
    System.out.println("Consumer Secret keys : [" + com.afrisoftech.hospital.HospitalMain.oAuthKey + "]");
    byte[] bytes = null;
    try {//from   w  w w. j a v  a2 s  .  c  om
        bytes = appKeySecret.getBytes("ISO-8859-1");
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(Base64Encoding.class.getName()).log(Level.SEVERE, null, ex);
    }
    String auth = Base64.toBase64String(bytes);

    OkHttpClient client = new OkHttpClient();
    System.out.println("New oAuth Access Token : [" + auth + "]");

    Request request = null;
    System.out.println("OkHttpClient : [" + client + "]");
    if (com.afrisoftech.hospital.HospitalMain.mobileTxTest) {
        request = new Request.Builder()
                .url("https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials").get()
                .addHeader("authorization", "Basic " + auth).addHeader("cache-control", "no-cache").build();
    } else {
        request = new Request.Builder()
                .url("https://api.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials").get()
                .addHeader("authorization", "Basic " + auth).addHeader("cache-control", "no-cache").build();
    }

    String accessToken = null;

    Response response;

    try {
        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 : " + myObject.toString());

        try {
            System.out.println("Access Token : [" + myObject.getString("access_token") + "]");

            accessToken = myObject.getString("access_token");

        } catch (JSONException e) {
            e.printStackTrace();
        }

    } catch (IOException ex) {
        ex.printStackTrace();
        javax.swing.JOptionPane.showMessageDialog(null,
                "There is a problem connecting to mobile payments service provider. Please contact system administrator");
    }

    return accessToken;

}

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

public String getOAuthAccessToken() {
    String accessToken = null;//from  w w w. java  2s. c  om
    String app_key = "Si1Y0dik7IoBEFC9buVTGBBdM0A9mQLw";
    String app_secret = "DlPLOhUtuwdAjzDB";
    String appKeySecret = app_key + ":" + app_secret;
    String auth = null;
    byte[] bytes = null;

    try {
        //bytes = usernameAndPassword.getBytes("ISO-8859-1");
        bytes = appKeySecret.getBytes("ISO-8859-1");
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(MobilePayAPI.class.getName()).log(Level.SEVERE, null, ex);
    }
    auth = com.itextpdf.text.pdf.codec.Base64.encodeBytes(bytes);//Base64.toBase64String(bytes);
    auth = auth.trim();
    System.out.println(bytes);
    System.out.println("Athentication : [" + auth + "]");

    // String auth = Base64.encode(bytes);
    OkHttpClient client = new OkHttpClient();

    System.out.println("OkHttpClient : [" + client + "]");

    Request request = new Request.Builder()
            .url("https://api.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials")
            // https://api.safaricom.co.ke/oauth/v1/generate
            // .url("https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials")
            .get().addHeader("Authorization", "Basic " + auth).addHeader("cache-control", "no-cache").build();
    System.out.println("Request : [" + request + "]");
    Response response;
    // String accessToken = null;
    try {
        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 : " + myObject.toString());

        try {
            System.out.println("Access Token : [" + myObject.getString("access_token") + "]");

            accessToken = myObject.getString("access_token");

        } catch (JSONException e) {
            e.printStackTrace();
        }

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

    return accessToken;
}

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

public void sendPaymentRequest(String accessToken) {

    OkHttpClient client = new OkHttpClient();

    MediaType mediaType = MediaType.parse("application/json");
    String message = null;/*from   w ww.  j  a va2s  .  c o  m*/
    JSONObject json = new JSONObject();
    try {
        json.put("InitiatorName", "Charles Waweru");
        json.put("SecurityCredential", this.encryptInitiatorPassword("cert.cer", "3414"));
        json.put("CommandID", "CustomerPayBillOnline");
        json.put("Amount", "10");
        json.put("PartyA", "254714433693");
        json.put("PartyB", "881100");
        json.put("Remarks", "Testing Rest API");
        json.put("QueueTimeOutURL", "");
        json.put("ResultURL",
                "https://192.162.85.226:17933/FunsoftWebServices/funsoft/InvoiceService/mpesasettlement");
        json.put("Occasion", "1234567891");
        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/b2c/v1/paymentrequest")
            .post(body).addHeader("authorization", "Bearer " + accessToken)
            .addHeader("content-type", "application/json").build();

    try {
        System.out.println("Request Build Security Credentials : ["
                + this.encryptInitiatorPassword("cert.cer", "3414") + "]");
        System.out.println("Request Build : [" + request.body().toString() + "]");
        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("Payment Request Response : " + myObject.toString());

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

}

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

public void simulateTransaction(String accessToken) {
    System.out.println("Access token to use : [" + accessToken + "]");
    OkHttpClient client = new OkHttpClient();

    MediaType mediaType = MediaType.parse("application/json");
    RequestBody body = RequestBody.create(mediaType,
            "{\"ShortCode\":\"881100\"," + "  \"CommandID\":\"CustomerPayBillOnline\"," + "  \"Amount\":\"1\","
                    + "  \"Msisdn\":\"254714433693\"," + "  \"BillRefNumber\":\"1234567890\" }");
    Request request = new Request.Builder().url("https://sandbox.safaricom.co.ke/mpesa/c2b/v1/simulate")
            .post(body).addHeader("authorization", "Bearer " + accessToken.trim())
            .addHeader("content-type", "application/json").build();

    try {//from   w  w  w . j  av a 2 s  . c  om
        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 simulate transaction : [" + myObject.toString() + "]\n\n");

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

}

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

public static boolean sendProcessRequest(String accessToken, String accountNo, String payerMobilePhone,
        String billedAmount, String shortCode) {
    boolean checkoutRequestStatus = true;
    OkHttpClient client = new OkHttpClient();
    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    dateFormat.setCalendar(calendar);/*from w ww  .  j  a  v  a2s . c  o m*/
    String timeStamp = dateFormat.format(calendar.getTime());
    System.out.println("Timestamp : [" + dateFormat.format(calendar.getTime()) + "]");
    System.out.println("Shortcode : [" + shortCode + "]");
    String password = shortCode + com.afrisoftech.hospital.HospitalMain.passKey + timeStamp;
    //        String password = shortCode + "48d34200abe6ebbcbc3bc644487c3651936d129f2274f6ee95" + timeStamp;
    //            json.put("CallBackURL", "https://192.162.85.226:17933/FunsoftWebServices/funsoft/InvoiceService/mpesasettlement");
    //        String password = shortCode + "bfb279f9aa9bdbcf158e97dd71a467cd2e0c893059b10f78e6b72ada1ed2c919" + timeStamp; // for testing purposes
    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", shortCode);
        json.put("Password", encodedPassword);
        json.put("Timestamp", timeStamp);
        json.put("TransactionType", "CustomerPayBillOnline");
        json.put("Amount", billedAmount);
        json.put("PartyA", payerMobilePhone);
        json.put("PartyB", shortCode);
        json.put("PhoneNumber", payerMobilePhone);
        json.put("CallBackURL", com.afrisoftech.hospital.HospitalMain.callBackURL);
        //            json.put("CallBackURL", "https://192.162.85.226:17933/FunsoftWebServices/funsoft/InvoiceService/mpesasettlement");
        json.put("AccountReference", accountNo);
        json.put("TransactionDesc", "Settlement for client bill");
        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/stkpush/v1/processrequest") // 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/stkpush/v1/processrequest")
                .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;
                com.afrisoftech.hospital.GeneralBillingIntfr.checkoutRequestID = myJsonObject
                        .getString("CheckoutRequestID");
                com.afrisoftech.hospinventory.PatientsBillingIntfr.checkoutRequestID = myJsonObject
                        .getString("CheckoutRequestID");
                com.afrisoftech.accounting.InpatientDepositIntfr.checkoutRequestID = myJsonObject
                        .getString("CheckoutRequestID");
                com.afrisoftech.accounting.InpatientRecpIntfr.checkoutRequestID = myJsonObject
                        .getString("CheckoutRequestID");
                com.afrisoftech.hospital.HospitalMain.checkoutRequestID = myJsonObject
                        .getString("CheckoutRequestID");
                com.afrisoftech.accounting.GovBillPaymentsIntfr.checkoutRequestID = myJsonObject
                        .getString("CheckoutRequestID");
                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;
}