List of usage examples for com.squareup.okhttp OkHttpClient OkHttpClient
public OkHttpClient()
From source file:fiskinfoo.no.sintef.fiskinfoo.Http.BarentswatchApiRetrofit.BarentswatchApi.java
License:Apache License
public Request getRequestForAuthenticationClientCredentialsFlow(String mEmail, String mPassword) { final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json;charset=utf-8"); final OkHttpClient client = new OkHttpClient(); RequestBody formBody = new FormEncodingBuilder().add("grant_type", "client_credentials") .add("client_id", mEmail).add("client_secret", mPassword).build(); return new Request.Builder().url(currentPath + "/api/token") .header("content-type", "application/x-www-form-urlencoded").post(formBody).build(); }
From source file:fm.feed.android.playersdk.service.webservice.Webservice.java
License:Open Source License
public Webservice(Context context) { String apiVersion = context.getString(R.string.api_version); String apiUrl = context.getString(R.string.api_url); OkHttpClient okHttpClient = new OkHttpClient(); gson = new GsonBuilder().registerTypeAdapter(FeedFMError.class, new FeedFMErrorDeserializer()).create(); RestAdapter restAdapter = new RestAdapter.Builder().setLogLevel(RestAdapter.LogLevel.BASIC) .setClient(new OkClient(okHttpClient)).setExecutors(Executors.newSingleThreadExecutor(), null) .setEndpoint(apiUrl + apiVersion) .setConverter(new GsonConverter(gson)).setRequestInterceptor(new AddClientIdRequestInterceptor()) .build();//from ww w . j a v a 2s. com mRestService = restAdapter.create(RestInterface.class); }
From source file:fr.eo.api.ApiErrorTest.java
License:Open Source License
@Ignore @Test(expected = RetrofitError.class) public void testTimeout() throws FileNotFoundException { OkHttpClient client = new OkHttpClient(); client.setConnectTimeout(1, TimeUnit.MILLISECONDS); client.setReadTimeout(1, TimeUnit.MILLISECONDS); AccountService accountService = new Manager().setClient(new OkClient(client)) .setErrorHandler(new NetworkErrorHandler() { @Override//w w w .j av a2s . c om public void onNoInternetError(RetrofitError cause) { System.err.println("No internet connection !"); } @Override public void onTimeOutError(RetrofitError cause) { assertTrue(true); } }).accountService(); TestCredential testCredential = getCredential(); accountService.apiKeyInfo(testCredential.keyID, testCredential.vCode); fail("No error occured !"); }
From source file:fr.eo.api.ApiErrorTest.java
License:Open Source License
@Ignore @Test(expected = RetrofitError.class) public void testNoInternet() throws FileNotFoundException { OkHttpClient client = new OkHttpClient(); client.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("toto", 1234))); AccountService accountService = new Manager().setClient(new OkClient(client)) .setErrorHandler(new NetworkErrorHandler() { @Override/*w ww . j a va 2 s . c o m*/ public void onNoInternetError(RetrofitError cause) { assertTrue(true); } @Override public void onTimeOutError(RetrofitError cause) { fail("No Time out here !"); } }).accountService(); TestCredential testCredential = getCredential(); accountService.apiKeyInfo(testCredential.keyID, testCredential.vCode); fail("No error occured !"); }
From source file:hku.fyp14017.blencode.web.ConnectionWrapper.java
License:Open Source License
public String doHttpsPostFileUpload(String urlString, HashMap<String, String> postValues, String fileTag, String filePath, ResultReceiver receiver, Integer notificationId) throws IOException, WebconnectionException { String answer = ""; String fileName = postValues.get(TAG_PROJECT_TITLE); String username = postValues.get(Constants.USERNAME); String description = postValues.get("projectDescription"); if (filePath != null) { OkHttpClient okHttpClient = new OkHttpClient(); okHttpClient.setTransports(Arrays.asList("http/1.1")); HttpRequest.setConnectionFactory(new OkConnectionFactory(okHttpClient)); HttpRequest uploadRequest = HttpRequest.post(urlString).chunk(0); for (HashMap.Entry<String, String> entry : postValues.entrySet()) { uploadRequest.part(entry.getKey(), entry.getValue()); }//from w w w .j av a2 s.c o m File file = new File(filePath); uploadRequest.part(fileTag, fileName, file); //This is the Parse cloud upload byte[] fileData = new byte[(int) file.length()]; FileInputStream fis = new FileInputStream(file); fis.read(fileData); fis.close(); ParseFile pf = new ParseFile(fileName + ".zip", fileData); try { pf.save(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } ParseObject parseZipFile = new ParseObject("bleProjects"); parseZipFile.put("username", username); parseZipFile.put("projectName", fileName); parseZipFile.put("description", description); parseZipFile.put("zipFileData", pf); try { parseZipFile.save(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } //ENDOF Parse cloud upload try { int responseCode = uploadRequest.code(); if (!(responseCode == 200 || responseCode == 201)) { throw new WebconnectionException(responseCode, "Error response code should be 200 or 201!"); } if (!uploadRequest.ok()) { Log.v(TAG, "Upload not successful"); StatusBarNotificationManager.getInstance().cancelNotification(notificationId); } else { StatusBarNotificationManager.getInstance().showOrUpdateNotification(notificationId, 100); } answer = uploadRequest.body(); Log.v(TAG, "Upload response is: " + answer); } catch (HttpRequest.HttpRequestException exception) { Log.e(TAG, "OkHttpError", exception); throw new WebconnectionException(WebconnectionException.ERROR_NETWORK, "OkHttp threw an exception"); } } return answer; }
From source file:info.curtbinder.notificationmanager.CommTask.java
License:Open Source License
@Override public void run() { try {//from ww w. j a v a 2s .co m URL url = new URL(host.toString()); OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(url).build(); Response response = client.newCall(request).execute(); XMLNotificationHandler xml = new XMLNotificationHandler(); SAXParserFactory spf = SAXParserFactory.newInstance(); XMLReader xr = spf.newSAXParser().getXMLReader(); xr.setContentHandler(xml); String r = response.body().string(); Intent i = new Intent(); if (r.equals("Done")) { // we got a positive response from our update i.setAction(MessageCommands.SERVER_RESPONSE); String msg; int p1Id; String fmt = ctx.getString(R.string.success_msg); switch (host.getType()) { default: case Host.ADD: p1Id = R.string.added; break; case Host.UPDATE: p1Id = R.string.updated; break; case Host.DELETE: p1Id = R.string.deleted; break; } msg = String.format(fmt, ctx.getString(p1Id), host.getAlertName()); i.putExtra(MessageCommands.MSG_RESPONSE, msg); } else { xr.parse(new InputSource(new StringReader(r))); i.setAction(MessageCommands.UPDATE_DISPLAY_ALERTS); i.putParcelableArrayListExtra("ALERTS", (ArrayList) xml.getAlerts()); } response.body().close(); // send message to main thread with the data ctx.sendBroadcast(i); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } }
From source file:info.curtbinder.reefangel.service.ControllerTask.java
License:Creative Commons License
public void run() { // Communicate with controller // clear out the error code on run rapp.clearErrorCode();//from ww w . j a va2s. com Response response = null; boolean fInterrupted = false; broadcastUpdateStatus(R.string.statusStart); try { URL url = new URL(host.toString()); OkHttpClient client = new OkHttpClient(); client.setConnectTimeout(host.getConnectTimeout(), TimeUnit.MILLISECONDS); client.setReadTimeout(host.getReadTimeout(), TimeUnit.MILLISECONDS); Request.Builder builder = new Request.Builder(); builder.url(url); if (host.isDeviceAuthenticationEnabled()) { String creds = Credentials.basic(host.getWifiUsername(), host.getWifiPassword()); builder.header("Authorization", creds); } Request req = builder.build(); broadcastUpdateStatus(R.string.statusConnect); response = client.newCall(req).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); if (Thread.interrupted()) throw new InterruptedException(); } catch (MalformedURLException e) { rapp.error(1, e, "MalformedURLException"); } catch (SocketTimeoutException e) { rapp.error(5, e, "SocketTimeoutException"); } catch (ConnectException e) { rapp.error(3, e, "ConnectException"); } catch (UnknownHostException e) { String msg = "Unknown Host: " + host.toString(); UnknownHostException ue = new UnknownHostException(msg); rapp.error(4, ue, "UnknownHostException"); } catch (EOFException e) { EOFException eof = new EOFException(rapp.getString(R.string.errorAuthentication)); rapp.error(3, eof, "EOFException"); } catch (IOException e) { rapp.error(3, e, "IOException"); } catch (InterruptedException e) { fInterrupted = true; } processResponse(response, fInterrupted); }
From source file:info.rmapproject.cos.osf.client.service.OsfClientService.java
License:Apache License
/** * Instantiates a new osf client service. *///from w w w.j a va 2s. c o m public OsfClientService() { try { // Create object mapper ObjectMapper objectMapper = new ObjectMapper(); OkHttpClient client = new OkHttpClient(); ResourceConverter converter = new ResourceConverter(objectMapper, LightNode.class, LightRegistration.class, Registration.class, Identifier.class, Contributor.class, User.class, LightUser.class, Institution.class, Node.class); converter.setGlobalResolver(relUrl -> { System.err.println("Resolving " + relUrl); com.squareup.okhttp.Call req = client.newCall(new Request.Builder().url(relUrl).build()); try { byte[] bytes = req.execute().body().bytes(); return bytes; } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } }); RetrofitOsfServiceFactory factory = new RetrofitOsfServiceFactory("classpath*:/osf-config.json"); osfService = factory.getOsfService(OsfService.class); } catch (Exception e) { throw new RuntimeException("Could not start OSF Service", e); } }
From source file:inforuh.eventfinder.sync.SyncAdapter.java
License:Open Source License
@Override public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {//from w w w . j a v a2 s . com Log.d(LOG_TAG, "Getting event data..."); OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(Config.URL).build(); client.newCall(request).enqueue(this); }
From source file:io.apiman.common.net.hawkular.HawkularMetricsClient.java
License:Apache License
/** * Constructor.// w w w .jav a 2 s . c o m * @param metricsServer */ public HawkularMetricsClient(URL metricsServer) { this.serverUrl = metricsServer; httpClient = new OkHttpClient(); httpClient.setReadTimeout(DEFAULT_READ_TIMEOUT, TimeUnit.SECONDS); httpClient.setWriteTimeout(DEFAULT_WRITE_TIMEOUT, TimeUnit.SECONDS); httpClient.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT, TimeUnit.SECONDS); httpClient.setFollowRedirects(true); httpClient.setFollowSslRedirects(true); httpClient.setProxySelector(ProxySelector.getDefault()); httpClient.setCookieHandler(CookieHandler.getDefault()); httpClient.setCertificatePinner(CertificatePinner.DEFAULT); httpClient.setAuthenticator(AuthenticatorAdapter.INSTANCE); httpClient.setConnectionPool(ConnectionPool.getDefault()); httpClient.setProtocols(Util.immutableList(Protocol.HTTP_1_1)); httpClient.setConnectionSpecs(DEFAULT_CONNECTION_SPECS); httpClient.setSocketFactory(SocketFactory.getDefault()); Internal.instance.setNetwork(httpClient, Network.DEFAULT); }