List of usage examples for com.squareup.okhttp RequestBody create
public static RequestBody create(final MediaType contentType, final File file)
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 .java 2 s . c o m*/ 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 w w . 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; }
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 a 2 s . c om 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 a va 2 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
@SuppressWarnings("deprecation") private static void setConnectionParametersForRequest(com.squareup.okhttp.Request.Builder builder, Request<?> request) throws IOException, AuthFailureError { switch (request.getMethod()) { case Request.Method.DEPRECATED_GET_OR_POST: // Ensure backwards compatibility. Volley assumes a request with a null body is a GET. byte[] postBody = request.getPostBody(); if (postBody != null) { builder.post(RequestBody.create(MediaType.parse(request.getPostBodyContentType()), postBody)); }/*w w w . j a v a 2 s.c o m*/ break; case Request.Method.GET: builder.get(); break; case Request.Method.DELETE: builder.delete(); break; case Request.Method.POST: builder.post(createRequestBody(request)); break; case Request.Method.PUT: builder.put(createRequestBody(request)); break; case Request.Method.HEAD: builder.head(); break; case Request.Method.OPTIONS: builder.method("OPTIONS", null); break; case Request.Method.TRACE: builder.method("TRACE", null); break; case Request.Method.PATCH: builder.patch(createRequestBody(request)); break; default: throw new IllegalStateException("Unknown method type."); } }
From source file:com.aix.city.comm.OkHttpStack.java
License:Open Source License
private static RequestBody createRequestBody(Request r) throws AuthFailureError { final byte[] body = r.getBody(); if (body == null) return null; return RequestBody.create(MediaType.parse(r.getBodyContentType()), body); }
From source file:com.android.cloudfiles.cloudfilesforandroid.CloudFiles.java
License:Apache License
private Response createBucket(String region, String bucket) throws IOException { RequestBody body = RequestBody.create(IMAGE, ""); Request request = new Request.Builder().url(urls.get(region) + "/" + bucket) .header("X-Auth-Token", getToken()).put(body).build(); client.newCall(request).execute();/* w ww .j av a 2s . c o m*/ body = RequestBody.create(IMAGE, ""); request = new Request.Builder().url(cdnUrls.get(region) + "/" + bucket).header("X-Auth-Token", getToken()) .addHeader("X-Cdn-Enabled", "True").put(body).build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); 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.anony.okhttp.sample.PostFile.java
License:Apache License
public void run() throws Exception { File file = new File("README.md"); Request request = new Request.Builder().url("https://api.github.com/markdown/raw") .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file)).build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); System.out.println(response.body().string()); }
From source file:com.anony.okhttp.sample.PostMultipart.java
License:Apache License
public void run() throws Exception { // Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM) .addFormDataPart("title", "Square Logo").addFormDataPart("image", null, RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png"))) .build();// w w w.ja v a 2s . co m Request request = new Request.Builder().header("Authorization", "Client-ID " + IMGUR_CLIENT_ID) .url("https://api.imgur.com/3/image").post(requestBody).build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); System.out.println(response.body().string()); }