List of usage examples for com.squareup.okhttp OkHttpClient OkHttpClient
public OkHttpClient()
From source file:com.commonsware.android.okhttp.LoadThread.java
License:Apache License
@Override public void run() { try {//w w w . j av a 2s.c o m OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(SO_URL).build(); Response response = client.newCall(request).execute(); if (response.isSuccessful()) { Reader in = response.body().charStream(); BufferedReader reader = new BufferedReader(in); SOQuestions questions = new Gson().fromJson(reader, SOQuestions.class); reader.close(); EventBus.getDefault().post(new QuestionsLoadedEvent(questions)); } else { Log.e(getClass().getSimpleName(), response.toString()); } } catch (Exception e) { Log.e(getClass().getSimpleName(), "Exception parsing JSON", e); } }
From source file:com.coviu.core.ApiClient.java
License:Apache License
private void init() { httpClient = new OkHttpClient(); verifyingSsl = true;/*w w w. ja va 2 s.c om*/ json = new JSON(this); /* * Use RFC3339 format for date and datetime. * See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 */ this.dateFormat = new SimpleDateFormat("yyyy-MM-dd"); // Always use UTC as the default time zone when dealing with date (without time). this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); initDatetimeFormat(); // Be lenient on datetime formats when parsing datetime from string. // See <code>parseDatetime</code>. this.lenientDatetimeFormat = true; // Set default User-Agent. setUserAgent("Coviu-Api-Client/1.0-SNAPSHOT/java"); // Setup authentications (key: authentication name, value: authentication). authentications = new HashMap<String, Authentication>(); authentications.put("oauth2", new OAuth()); // Prevent the authentications from being modified. authentications = Collections.unmodifiableMap(authentications); }
From source file:com.creapple.tms.mobiledriverconsole.utils.MDCUtils.java
License:Creative Commons License
/** * Get distance information between two GPS * @param originLat//from w ww . j a v a 2 s .c o m * @param originLon * @param destLat * @param destLon * @return */ public static String[] getDistanceInfo(double originLat, double originLon, double destLat, double destLon) { String[] infos = new String[] { "0", "0" }; String address = Constants.GOOGLE_DISTANCE_MATRIX_ADDRESS; address += originLat + "," + originLon; address += "&destinations="; address += destLat + "," + destLon; address += "&mode=driving&units=metric&language=en&key="; address += Constants.GOOGLE_DISTANCE_MATRIX_API_KEY; OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(address).build(); Response response = null; String dist = null; try { response = client.newCall(request).execute(); dist = response.body().string(); } catch (IOException e) { return infos; } Log.d("@@@@@@", dist); JSONParser jsonParser = new JSONParser(); JSONObject jsonObject = null; try { jsonObject = (JSONObject) jsonParser.parse(dist); } catch (ParseException e) { return infos; } // status check as well JSONArray rows = (JSONArray) jsonObject.get(Constants.GOOGLE_DISTANCE_MATRIX_ROWS); for (int i = 0; i < rows.size(); i++) { JSONObject obj = (JSONObject) rows.get(i); JSONArray elements = (JSONArray) obj.get(Constants.GOOGLE_DISTANCE_MATRIX_ELEMENTS); for (int j = 0; j < elements.size(); j++) { JSONObject datas = (JSONObject) elements.get(j); JSONObject distance = (JSONObject) datas.get(Constants.GOOGLE_DISTANCE_MATRIX_DISTANCE); JSONObject duration = (JSONObject) datas.get(Constants.GOOGLE_DISTANCE_MATRIX_DURATION); infos[0] = distance.get(Constants.GOOGLE_DISTANCE_MATRIX_VALUE) + ""; infos[1] = duration.get(Constants.GOOGLE_DISTANCE_MATRIX_TEXT) + ""; } } String status = jsonObject.get(Constants.GOOGLE_DISTANCE_MATRIX_STATUS).toString(); // Log.d("@@@@@@", status); if (!StringUtils.equalsIgnoreCase(Constants.GOOGLE_DISTANCE_MATRIX_OK, status)) { return infos; } return infos; }
From source file:com.cuddlesoft.norilib.service.ServiceTypeDetectionService.java
@Override protected void onHandleIntent(Intent intent) { // Extract SearchClient.Settings from the received Intent. final Uri uri = Uri.parse(intent.getStringExtra(ENDPOINT_URL)); final Intent broadcastIntent = new Intent(ACTION_DONE); if (uri.getHost() == null || uri.getScheme() == null) { // The URL supplied is invalid. sendBroadcast(broadcastIntent.putExtra(RESULT_CODE, RESULT_FAIL_INVALID_URL)); return;/*from ww w . j a va 2s.c om*/ } // Create the HTTP client. final OkHttpClient okHttpClient = new OkHttpClient(); okHttpClient.setConnectTimeout(REQUEST_TIMEOUT, TimeUnit.SECONDS); okHttpClient.setReadTimeout(REQUEST_TIMEOUT, TimeUnit.SECONDS); // Iterate over supported URI schemes for given URL. for (String uriScheme : (TLS_SUPPORT.contains(uri.getHost()) ? URI_SCHEMES_PREFER_SSL : URI_SCHEMES)) { String baseUri = uriScheme + uri.getHost(); // Iterate over each endpoint path. for (Map.Entry<SearchClient.Settings.APIType, String> entry : API_ENDPOINT_PATHS.entrySet()) { // Create a HTTP request object. final Request request = new Request.Builder().url(baseUri + entry.getValue()).build(); try { // Fetch response. final Response response = okHttpClient.newCall(request).execute(); // Make sure the response code was OK and that the HTTP client wasn't redirected along the way. if (response.code() == HttpStatus.SC_OK && response.priorResponse() == null) { // Found an API endpoint. broadcastIntent.putExtra(RESULT_CODE, RESULT_OK); broadcastIntent.putExtra(ENDPOINT_URL, baseUri); broadcastIntent.putExtra(API_TYPE, entry.getKey().ordinal()); sendBroadcast(broadcastIntent); return; } } catch (IOException e) { // Network error. Notify the listeners and return. sendBroadcast(broadcastIntent.putExtra(RESULT_CODE, RESULT_FAIL_NETWORK)); return; } } } // End of the loop was reached without finding an API endpoint. Send error code to the BroadcastReceiver. sendBroadcast(broadcastIntent.putExtra(RESULT_CODE, RESULT_FAIL_NO_API)); }
From source file:com.davidecirillo.dashboard.data.RestService.java
License:Apache License
public void create() { final OkHttpClient client = new OkHttpClient(); HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); if (BuildConfig.DEBUG) loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); else// ww w . ja v a 2 s . c o m loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.NONE); List<Interceptor> interceptors = new ArrayList<>(); interceptors.add(loggingInterceptor); interceptors.add(new LoggingInterceptor() { @Override public Response intercept(Chain chain) throws IOException { Request original = chain.request(); Request request = original.newBuilder().method(original.method(), original.body()).build(); return chain.proceed(request); } }); client.networkInterceptors().addAll(interceptors); retrofit.Retrofit restAdapterLocal = new retrofit.Retrofit.Builder().client(client) .baseUrl(AppConfig.http + mLocalUrl).addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build(); retrofit.Retrofit restAdapterRemote = new retrofit.Retrofit.Builder().client(client) .baseUrl(AppConfig.http + mRemoteUrl).addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build(); mLocalPiApi = restAdapterLocal.create(PIApi.class); mRemotePiApi = restAdapterRemote.create(PIApi.class); }
From source file:com.digi.wva.internal.HttpClient.java
License:Mozilla Public License
/** Constructor * * @param hostname The hostname/IP address of the WVA. *//*from ww w .j a v a2s. co m*/ public HttpClient(String hostname) { this.client = new OkHttpClient(); client.setSslSocketFactory(makeSSLSocketFactory()).setHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }); this.hostname = hostname; }
From source file:com.digitalglobe.iipfoundations.productservice.gbdx.GBDxAComp.java
public static String requestACompWorkflow(String input_directory, String output_directory, String authorization) {/* ww w . j a va2 s.co m*/ String workflow = generateACompRequestBody(input_directory, output_directory); System.out.println(workflow); MediaType mediaType = MediaType.parse("application/json"); RequestBody request_body = RequestBody.create(mediaType, workflow); //Properties gbdx = GBDxCredentialManager.getGBDxCredentials(); Request search_request = new Request.Builder().url("https://geobigdata.io/workflows/v1/workflows") .post(request_body).addHeader("content-type", "application/json") .addHeader("authorization", authorization).build(); OkHttpClient client = new OkHttpClient(); String id = ""; try { Response response = client.newCall(search_request).execute(); String body = response.body().string(); JSONObject obj = new JSONObject(body); id = obj.getString("id"); } catch (IOException e) { e.printStackTrace(System.out); System.exit(0); } return id; }
From source file:com.digitalglobe.iipfoundations.productservice.gbdx.GBDxCatalogQuery.java
public static void main(String[] args) { OkHttpClient client = new OkHttpClient(); client.setHostnameVerifier(new HostnameVerifier() { @Override// w ww .ja v a 2 s .c o m public boolean verify(String hostname, SSLSession session) { return true; } }); Request request = new Request.Builder().url("https://geobigdata.io/catalog/v1/record/105041001281F200") .get().addHeader("content-type", "application/json") .addHeader("authorization", GBDxCredentialManager.getAuthorizationHeader()).build(); try { Response response = client.newCall(request).execute(); String body = response.body().string(); System.out.println(body); // PrintWriter out = new PrintWriter("catalog.json"); // out.println(body); // out.flush(); // out.close(); JSONObject obj = new JSONObject(body); String available = obj.getJSONObject("properties").getString("available"); System.out.println(available); // JSONArray arr = obj.getJSONArray("posts"); // for (int i = 0; i < arr.length(); i++) { // String post_id = arr.getJSONObject(i).getString("post_id"); // ...... // } MediaType mediaType = MediaType.parse("application/json"); RequestBody request_body = RequestBody.create(mediaType, "{ \n \"startDate\":null,\n \"endDate\": null,\n \"searchAreaWkt\":null,\n \"tagResults\": false,\n \"filters\": [\"identifier = '105041001281F200'\"],\n \"types\":[\"Acquisition\"]\n}"); Request search_request = new Request.Builder().url("https://alpha.geobigdata.io/catalog/v1/search") .post(request_body).addHeader("content-type", "application/json") .addHeader("authorization", GBDxCredentialManager.getAuthorizationHeader()).build(); response = client.newCall(search_request).execute(); body = response.body().string(); System.out.println(body); // PrintWriter out = new PrintWriter("search_result.json"); // out.println(body); // out.flush(); // out.close(); mediaType = MediaType.parse("application/json"); request_body = RequestBody.create(mediaType, "{\n \"rootRecordId\": \"105041001281F200\",\n \"maxdepth\": 2,\n \"direction\": \"both\",\n \"labels\": []\n }"); request = new Request.Builder().url("https://alpha.geobigdata.io/catalog/v1/traverse") .post(request_body).addHeader("content-type", "application/json") .addHeader("authorization", GBDxCredentialManager.getAuthorizationHeader()).build(); response = client.newCall(request).execute(); body = response.body().string(); System.out.println(body); PrintWriter out = new PrintWriter("traverse_result.json"); out.println(body); out.flush(); out.close(); } catch (IOException io) { System.out.println("ERROR!"); System.out.println(io.getMessage()); } }
From source file:com.digitalglobe.iipfoundations.productservice.gbdx.GBDxCredentialManager.java
public static Properties validateUserToken(String token) { Properties token_info = new Properties(); OkHttpClient client = new OkHttpClient(); client.setHostnameVerifier(new HostnameVerifier() { @Override//from w w w .jav a 2 s . c o m public boolean verify(String hostname, SSLSession session) { return true; } }); Request request = new Request.Builder().url("https://geobigdata.io/auth/v1/validate_token").get() .addHeader("content-type", "application/json").addHeader("authorization", "Bearer " + token) .build(); try { Response response = client.newCall(request).execute(); String body = response.body().string(); token_info = parseResponse(body); } catch (IOException io) { System.out.println("ERROR!"); System.out.println(io.getMessage()); } return token_info; }
From source file:com.digitalglobe.iipfoundations.productservice.gbdx.GBDxEventNotification.java
public synchronized void notifyWorkflowComplete(String workflow_id) { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url("https://geobigdata.io/workflows/v1/workflows/" + workflow_id) .get().addHeader("content-type", "application/json") .addHeader("authorization", GBDxCredentialManager.getAuthorizationHeader()).build(); try {//from w w w. ja v a 2 s .c o m // convert to thread, but for now use a loop and sleep for testing boolean isComplete = false; while (!isComplete) { Response response = client.newCall(request).execute(); String body = response.body().string(); System.out.println(body); JSONObject obj = new JSONObject(body); String state = obj.getJSONObject("state").getString("state"); System.out.println(state); if (state.equalsIgnoreCase("complete")) { isComplete = true; } else { try { Thread.sleep(5000); } catch (InterruptedException ex) { } } } } catch (IOException e) { System.out.println(e.getMessage()); System.exit(0); } }