List of usage examples for com.squareup.okhttp OkHttpClient OkHttpClient
public OkHttpClient()
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 ww w. j a va2s .c o m*/ 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. j ava 2 s . c o m*/ 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 w w .j a va 2 s. 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 ww. 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 ww w. j a v a 2s .co 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; }
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 . j ava 2s .co m 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) {//from ww w .ja va2 s .c om 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.alibaba.weex.commons.adapter.DefaultWebSocketAdapter.java
License:Apache License
@Override public void connect(String url, @Nullable String protocol, EventListener listener) { this.eventListener = listener; OkHttpClient okHttpClient = new OkHttpClient(); Request.Builder builder = new Request.Builder(); if (protocol != null) { builder.addHeader(HEADER_SEC_WEBSOCKET_PROTOCOL, protocol); }//from w w w.ja v a 2 s .c o m builder.url(url); WebSocketCall.create(okHttpClient, builder.build()).enqueue(new WebSocketListener() { @Override public void onOpen(WebSocket webSocket, Request request, Response response) throws IOException { ws = webSocket; eventListener.onOpen(); } @Override public void onMessage(BufferedSource payload, WebSocket.PayloadType type) throws IOException { eventListener.onMessage(payload.readUtf8()); payload.close(); } @Override public void onPong(Buffer payload) { } @Override public void onClose(int code, String reason) { eventListener.onClose(code, reason, true); } @Override public void onFailure(IOException e) { e.printStackTrace(); if (e instanceof EOFException) { eventListener.onClose(WebSocketCloseCodes.CLOSE_NORMAL.getCode(), WebSocketCloseCodes.CLOSE_NORMAL.name(), true); } else { eventListener.onError(e.getMessage()); } } }); }
From source file:com.alibaba.weex.update.Downloader.java
License:Apache License
public static void download(String url, final DownloadCallback callback) { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(url).get().build(); client.newCall(request).enqueue(new Callback() { @Override/*ww w . ja va2s . c om*/ public void onFailure(Request request, IOException e) { callback.onError(e); } @Override public void onResponse(Response response) throws IOException { callback.handleResponse(response); } }); }
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 w w. j av a2 s .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]); }