List of usage examples for com.squareup.okhttp OkHttpClient newCall
public Call newCall(Request request)
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 w w . j a v a 2s . c om*/ 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 w w.j a v a2 s . 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 w w w .j av a 2 s .co 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
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { OkHttpClient client = mClient.clone(); int timeoutMs = request.getTimeoutMs(); client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS); client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS); client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS); com.squareup.okhttp.Request.Builder okHttpRequestBuilder = new com.squareup.okhttp.Request.Builder(); okHttpRequestBuilder.url(request.getUrl()); Map<String, String> headers = request.getHeaders(); for (final String name : headers.keySet()) { okHttpRequestBuilder.addHeader(name, headers.get(name)); }//from w w w.j av a 2s . co m for (final String name : additionalHeaders.keySet()) { okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name)); } setConnectionParametersForRequest(okHttpRequestBuilder, request); com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build(); Call okHttpCall = client.newCall(okHttpRequest); Response okHttpResponse = okHttpCall.execute(); StatusLine responseStatus = new BasicStatusLine(parseProtocol(okHttpResponse.protocol()), okHttpResponse.code(), okHttpResponse.message()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromOkHttpResponse(okHttpResponse)); Headers responseHeaders = okHttpResponse.headers(); for (int i = 0, len = responseHeaders.size(); i < len; i++) { final String name = responseHeaders.name(i), value = responseHeaders.value(i); if (name != null) { response.addHeader(new BasicHeader(name, value)); } } return response; }
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/*from ww w . j a v a 2 s.co m*/ 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 {//w w w . j a v a 2 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]); }
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 . ja va 2 s . co 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.anony.okhttp.sample.PerCallSettings.java
License:Apache License
public void run() throws Exception { Request request = new Request.Builder().url("http://httpbin.org/delay/1") // This URL is served with a 1 second delay. .build();/* ww w .j a v a 2s .c om*/ try { OkHttpClient cloned = client.clone(); // Clone to make a customized OkHttp for this request. cloned.setReadTimeout(500, TimeUnit.MILLISECONDS); Response response = cloned.newCall(request).execute(); System.out.println("Response 1 succeeded: " + response); } catch (IOException e) { System.out.println("Response 1 failed: " + e); } try { OkHttpClient cloned = client.clone(); // Clone to make a customized OkHttp for this request. cloned.setReadTimeout(3000, TimeUnit.MILLISECONDS); Response response = cloned.newCall(request).execute(); System.out.println("Response 2 succeeded: " + response); } catch (IOException e) { System.out.println("Response 2 failed: " + e); } }
From source file:com.apothesource.pillfill.network.PFNetworkManager.java
License:Open Source License
public static String doPinnedGetForUrl(String url) throws IOException { OkHttpClient client = getPinnedPFHttpClient(); Request.Builder requestBuilder = new Request.Builder().url(url); Response response = client.newCall(requestBuilder.build()).execute(); return response.body().string(); }
From source file:com.apothesource.pillfill.network.PFNetworkManager.java
License:Open Source License
public static String doPinnedGetForUrl(String url, String authToken) throws IOException { OkHttpClient client = getPinnedPFHttpClient(); Request.Builder requestBuilder = new Request.Builder().url(url); if (authToken != null) requestBuilder = requestBuilder.addHeader("Bearer", authToken); Response response = client.newCall(requestBuilder.build()).execute(); return response.body().string(); }