List of usage examples for com.squareup.okhttp OkHttpClient newCall
public Call newCall(Request request)
From source file:cn.edu.zafu.news.ui.main.NewsFragment.java
License:Apache License
private void refreshData() { isRefreshing = true;// w w w. jav a 2 s. c om page = 1; OkHttpClient client = NewsOkHttpClient.getInstance(); final Request request = new Request.Builder().url(category.getUrl() + page).build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { handler.sendEmptyMessage(REFRESH_ERROR); } @Override public void onResponse(Response response) throws IOException { NewsParser newsParser = new NewsParser(); String str = response.body().string(); if (max == 0) { getMaxPage(str); } list.clear(); list.addAll(newsParser.convert(str)); handler.sendEmptyMessage(REFRESH); } }); }
From source file:cn.edu.zafu.news.ui.main.NewsFragment.java
License:Apache License
private synchronized void loadMore() { isLoadingMore = true;/*from www . j a v a2 s.c o m*/ if (page >= max) { Toast.makeText(getActivity(), "?", Toast.LENGTH_LONG).show(); return; } page++; OkHttpClient client = NewsOkHttpClient.getInstance(); final Request request = new Request.Builder().url(category.getUrl() + page).build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { handler.sendEmptyMessage(LOADMORE_ERROR); } @Override public void onResponse(Response response) throws IOException { NewsParser newsParser = new NewsParser(); list.addAll(newsParser.convert(response.body().string())); handler.sendEmptyMessage(LOADMORE); } }); }
From source file:co.aquario.socialkit.search.youtube.YouTubeData.java
License:Open Source License
/** * Calculate the YouTube URL to load the video. Includes retrieving a token that YouTube * requires to play the video./*w w w . j a va2 s. c o m*/ * * @param quality quality of the video. 17=low, 18=high * @param fallback whether to fallback to lower quality in case the supplied quality is not available * @param videoId the id of the video * @return the url string that will retrieve the video * @throws java.io.IOException */ public static String calculateYouTubeUrl(String quality, boolean fallback, String videoId) throws IOException { String uriStr = ""; OkHttpClient client = VMApp.getHttpClient(); Request.Builder request = new Request.Builder(); request.url(YOUTUBE_VIDEO_INFORMATION_URL + videoId); Call call = client.newCall(request.build()); Response response = call.execute(); String infoStr = response.body().string(); String[] args = infoStr.split("&"); Map<String, String> argMap = new HashMap<String, String>(); for (String arg : args) { String[] valStrArr = arg.split("="); if (valStrArr.length >= 2) { argMap.put(valStrArr[0], URLDecoder.decode(valStrArr[1])); } } //Find out the URI string from the parameters //Populate the listStory of formats for the video String fmtList = ""; if (argMap.get("fmt_list") == null) { return ""; } else { fmtList = URLDecoder.decode(argMap.get("fmt_list"), "utf-8"); } ArrayList<co.aquario.socialkit.util.Format> formats = new ArrayList<co.aquario.socialkit.util.Format>(); if (null != fmtList) { String formatStrs[] = fmtList.split(","); for (String lFormatStr : formatStrs) { co.aquario.socialkit.util.Format format = new co.aquario.socialkit.util.Format(lFormatStr); formats.add(format); } } //Populate the listStory of streams for the video String streamList = argMap.get("url_encoded_fmt_stream_map"); if (null != streamList) { String streamStrs[] = streamList.split(","); ArrayList<VideoStream> streams = new ArrayList<VideoStream>(); for (String streamStr : streamStrs) { VideoStream lStream = new VideoStream(streamStr); streams.add(lStream); } //Search for the given format in the listStory of video formats // if it is there, select the corresponding stream // otherwise if fallback is requested, check for next lower format int formatId = Integer.parseInt(quality); co.aquario.socialkit.util.Format searchFormat = new co.aquario.socialkit.util.Format(formatId); while (!formats.contains(searchFormat) && fallback) { int oldId = searchFormat.getId(); int newId = getSupportedFallbackId(oldId); if (oldId == newId) { break; } searchFormat = new co.aquario.socialkit.util.Format(newId); } int index = formats.indexOf(searchFormat); if (index >= 0) { VideoStream searchStream = streams.get(index); uriStr = searchStream.getUrl(); } } //Return the URI string. It may be null if the format (or a fallback format if enabled) // is not found in the listStory of formats for the video return uriStr; }
From source file:co.paralleluniverse.fibers.okhttp.test.utils.original.SocksProxyTest.java
License:Apache License
@Test public void proxy() throws Exception { server.enqueue(new MockResponse().setBody("abc")); server.enqueue(new MockResponse().setBody("def")); OkHttpClient client = new OkHttpClient().setProxy(socksProxy.proxy()); Request request1 = new Request.Builder().url(server.url("/")).build(); Response response1 = client.newCall(request1).execute(); assertEquals("abc", response1.body().string()); Request request2 = new Request.Builder().url(server.url("/")).build(); Response response2 = client.newCall(request2).execute(); assertEquals("def", response2.body().string()); // The HTTP calls should share a single connection. assertEquals(1, socksProxy.connectionCount()); }
From source file:co.paralleluniverse.fibers.okhttp.test.utils.original.SocksProxyTest.java
License:Apache License
@Test public void proxySelector() throws Exception { server.enqueue(new MockResponse().setBody("abc")); ProxySelector proxySelector = new ProxySelector() { @Override/*w w w . ja v a 2 s . c o m*/ public List<Proxy> select(URI uri) { return Collections.singletonList(socksProxy.proxy()); } @Override public void connectFailed(URI uri, SocketAddress socketAddress, IOException e) { throw new AssertionError(); } }; OkHttpClient client = new OkHttpClient().setProxySelector(proxySelector); Request request = new Request.Builder().url(server.url("/")).build(); Response response = client.newCall(request).execute(); assertEquals("abc", response.body().string()); assertEquals(1, socksProxy.connectionCount()); }
From source file:com.adnanbal.fxdedektifi.sample.data.net.ApiConnection.java
License:Apache License
private void connectToApi() { OkHttpClient okHttpClient = this.createClient(); final Request request = new Request.Builder().url(this.url) .addHeader(CONTENT_TYPE_LABEL, CONTENT_TYPE_VALUE_JSON).get().build(); try {//w ww. j a v a 2 s. c o m this.response = okHttpClient.newCall(request).execute().body().string(); } catch (IOException e) { e.printStackTrace(); } }
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 av a 2 s .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;//ww w.j ava2s . com 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;// w w w . j a v a 2 s.com 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 . ja va 2 s. com*/ 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(); } }