List of usage examples for com.squareup.okhttp OkHttpClient OkHttpClient
public OkHttpClient()
From source file:com.guerinet.stringparser.StringParser.java
License:Apache License
public static void main(String[] args) throws IOException { // Keep a list of all of the languages the Strings are in List<Language> languages = new ArrayList<>(); // The list of language Strings List<HeaderString> strings = new ArrayList<>(); // Url// w ww . j a v a 2 s. c o m String url = null; // True if it's for Android, false if it's for iOS Boolean android = null; // Read from the config file BufferedReader configReader = null; try { configReader = new BufferedReader(new FileReader("../config.txt")); } catch (FileNotFoundException e) { try { configReader = new BufferedReader(new FileReader("config.txt")); } catch (FileNotFoundException ex) { System.out.println("Error: Config file not found"); System.exit(-1); } } String line; while ((line = configReader.readLine()) != null) { if (line.startsWith(URL)) { // Get the URL url = line.replace(URL, "").trim(); } else if (line.startsWith(PLATFORM)) { // Get the platform: Remove the header String platformString = line.replace(PLATFORM, "").trim(); if (platformString.equalsIgnoreCase("android")) { // Android android = true; } else if (platformString.equalsIgnoreCase("ios")) { //iOS android = false; } else { // Not recognized System.out.println("Error: Platform must be either Android or iOS."); System.exit(-1); } } else if (line.startsWith(LANGUAGE)) { // Get the languages: remove the header and separate the language Id from the path String languageString = line.replace(LANGUAGE, "").trim(); String[] languageInfo = languageString.split(", "); if (languageInfo.length != 2) { System.out.println("Error: The following format has too few or too many " + "arguments for a language: " + languageString); System.exit(-1); } // Save it as a new language in the list of languages languages.add(new Language(languageInfo[0], languageInfo[1])); } } configReader.close(); // Make sure nothing is null if (url == null) { System.out.println("Error: URL Cannot be null"); System.exit(-1); } else if (android == null) { System.out.println("Error: You need to input a platform"); System.exit(-1); } else if (languages.isEmpty()) { System.out.println("Error: You need to add at least one language"); System.exit(-1); } // Connect to the URL System.out.println("Connecting to " + url); Request request = new Request.Builder().get().url(url).build(); Response response; try { response = new OkHttpClient().newCall(request).execute(); } catch (IOException e) { // Catch the exception here to be able to continue a build even if we are not connected System.out.println("IOException while connecting to the URL"); System.out.println("Error Message: " + e.getMessage()); return; } int responseCode = response.code(); System.out.println("Response Code: " + responseCode); if (responseCode == 200) { // Set up the CSV reader CsvListReader reader = new CsvListReader(new InputStreamReader(response.body().byteStream(), "UTF-8"), CsvPreference.EXCEL_PREFERENCE); // Get the header final String[] header = reader.getHeader(true); // First column will be key, so ignore it for (int i = 1; i < header.length; i++) { String string = header[i]; // Check if the string matches any of the languages parsed for (Language language : languages) { if (string.equals(language.getId())) { // If we find a match, set the column index for this language language.setColumnIndex(i); break; } } } // Make sure that all languages have an index for (Language language : languages) { if (language.getColumnIndex() == -1) { System.out.println("Error: " + language.getId() + " does not have any translations."); System.exit(-1); } } // Make a CellProcessor with the right length final CellProcessor[] processors = new CellProcessor[header.length]; // Go through each line of the CSV document into a list of objects. List<Object> currentLine; // The current line number (start at 2 since 1 is the header) int lineNumber = 2; while ((currentLine = reader.read(processors)) != null) { // Get the key from the current line String key = (String) currentLine.get(0); // Check if there's a key if (key == null || key.trim().isEmpty()) { System.out.println( "Warning: Line " + lineNumber + " does not have " + "a kay and will not be parsed"); // Increment the line number lineNumber++; // Move on to the new String continue; } // Check if this is a header if (key.trim().startsWith(HEADER_KEY)) { strings.add(new HeaderString(key.replace("###", "").trim(), lineNumber)); // Increment the line number and continue lineNumber++; continue; } // Add a new language String LanguageString languageString = new LanguageString(key.trim(), lineNumber); // Go through the languages, add each translation boolean allNull = true; for (Language language : languages) { languageString.addTranslation(language.getId(), (String) currentLine.get(language.getColumnIndex())); // If at least one language is not null, then they are not all null if (languageString.getString(language.getId()) != null) { allNull = false; } } // Check if all of the values are null if (allNull) { // Show a warning message System.out.println( "Warning: Line " + lineNumber + " has no " + "translations so it will not be parsed."); } else { strings.add(languageString); } // Increment the line number lineNumber++; } // Close the CSV reader reader.close(); // Check if there are any errors with the keys for (int i = 0; i < strings.size(); i++) { HeaderString string1 = strings.get(i); // Skip headers for the checks if (!(string1 instanceof LanguageString)) { continue; } // Check if there are any spaces in the keys if (string1.getKey().contains(" ")) { System.out.println("Error: Line " + string1.getLineNumber() + " contains a space in its key."); System.exit(-1); } // Check if there are any duplicates for (int j = i + 1; j < strings.size(); j++) { HeaderString string2 = strings.get(j); // If the keys are the same and it's not a header, show an error and stop if (string1.getKey().equals(string2.getKey())) { System.out.println("Error: Lines " + string1.getLineNumber() + " and " + string2.getLineNumber() + " have the same key."); System.exit(-1); } } } // Go through each language, and write the file PrintWriter writer; for (Language language : languages) { // Set up the writer for the given language, enforcing UTF-8 writer = new PrintWriter(language.getPath(), "UTF-8"); if (android) { processAndroidStrings(writer, language, strings); } else { processIOSStrings(writer, language, strings); } System.out.println("Wrote " + language.getId() + " to file: " + language.getPath()); writer.close(); } // Exit message System.out.println("Strings parsing complete"); } else { System.out.println("Error: Response Code not 200"); System.out.println("Response Message: " + response.message()); } }
From source file:com.guoxiaoxing.music.lastfmapi.RestServiceFactory.java
License:Open Source License
public static <T> T createStatic(final Context context, String baseUrl, Class<T> clazz) { final OkHttpClient okHttpClient = new OkHttpClient(); okHttpClient.setCache(new Cache(context.getApplicationContext().getCacheDir(), CACHE_SIZE)); okHttpClient.setConnectTimeout(40, TimeUnit.SECONDS); RequestInterceptor interceptor = new RequestInterceptor() { @Override//from w w w .j a va2 s . c o m public void intercept(RequestFacade request) { //7-days cache request.addHeader("Cache-Control", String.format("max-age=%d,max-stale=%d", Integer.valueOf(60 * 60 * 24 * 7), Integer.valueOf(31536000))); request.addHeader("Connection", "keep-alive"); } }; RestAdapter.Builder builder = new RestAdapter.Builder().setEndpoint(baseUrl) .setRequestInterceptor(interceptor).setClient(new OkClient(okHttpClient)); return builder.build().create(clazz); }
From source file:com.gzsll.downloads.DownloadThread.java
License:Apache License
/** * Executes the download in a separate thread *///from w w w .j av a 2s .c om public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); State state = new State(mInfo); OkHttpClient client = null; PowerManager.WakeLock wakeLock = null; int finalStatus = Downloads.STATUS_UNKNOWN_ERROR; try { PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE); wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.TAG); wakeLock.acquire(); if (Constants.LOGV) { Log.v(Constants.TAG, "initiating download for " + mInfo.mUri); } client = new OkHttpClient(); boolean finished = false; while (!finished) { Log.i(Constants.TAG, "Initiating request for download " + mInfo.mId); try { executeDownload(state, client, new Request.Builder().url(state.mRequestUri)); finished = true; } catch (RetryDownload exc) { // fall through } } if (Constants.LOGV) { Log.v(Constants.TAG, "download completed for " + mInfo.mUri); } finalizeDestinationFile(state); finalStatus = Downloads.STATUS_SUCCESS; } catch (StopRequest error) { // remove the cause before printing, in case it contains PII Log.w(Constants.TAG, "Aborting request for download " + mInfo.mId + ": " + error.getMessage()); finalStatus = error.mFinalStatus; // fall through to finally block } catch (Throwable ex) { // sometimes the socket code throws unchecked // exceptions Log.w(Constants.TAG, "Exception for id " + mInfo.mId + ": " + ex); finalStatus = Downloads.STATUS_UNKNOWN_ERROR; // falls through to the code that reports an error } finally { if (wakeLock != null) { wakeLock.release(); wakeLock = null; } if (client != null) { client = null; } cleanupDestination(state, finalStatus); notifyDownloadCompleted(finalStatus, state.mCountRetry, state.mRetryAfter, state.mGotData, state.mFilename, state.mNewUri, state.mMimeType); mInfo.mHasActiveThread = false; } }
From source file:com.he5ed.lib.cloudprovider.apis.BoxApi.java
License:Apache License
/** * Constructor for Box API//from ww w . j a v a 2s . c om * * @param account Box account to be used must be Box cloud type */ public BoxApi(Context context, Account account) { mContext = context; mAccount = account; mCloudProvider = CloudProvider.getInstance(mContext); mHttpClient = new OkHttpClient(); }
From source file:com.he5ed.lib.cloudprovider.apis.CloudDriveApi.java
License:Apache License
/** * Constructor for Cloud Drive API/*from ww w . j a va2s . co m*/ * * @param account to be used must be Cloud Drive type */ public CloudDriveApi(Context context, Account account) { mContext = context; mAccount = account; mCloudProvider = CloudProvider.getInstance(mContext); mHttpClient = new OkHttpClient(); }
From source file:com.he5ed.lib.cloudprovider.apis.DropboxApi.java
License:Apache License
/** * Constructor for Dropbox API/* w ww. j av a 2s .co m*/ * * @param account Box account to be used must be Box cloud type */ public DropboxApi(Context context, Account account) { mContext = context; mAccount = account; mCloudProvider = CloudProvider.getInstance(mContext); mHttpClient = new OkHttpClient(); }
From source file:com.he5ed.lib.cloudprovider.apis.OneDriveApi.java
License:Apache License
/** * Constructor for OneDrive API//from w w w .j av a 2 s .c o m * * @param account to be used must be OneDrive cloud type */ public OneDriveApi(Context context, Account account) { mContext = context; mAccount = account; mCloudProvider = CloudProvider.getInstance(mContext); mHttpClient = new OkHttpClient(); }
From source file:com.he5ed.lib.cloudprovider.auth.OAuth2Fragment.java
License:Apache License
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // retain web view state during rotation setRetainInstance(true);/* ww w . j av a2s . co m*/ // get extra from intent Intent intent = getActivity().getIntent(); if (intent != null) { mCloudApi = intent.getStringExtra(OAuth2Activity.EXTRA_CLOUD_API); } else { // end activity getActivity().finish(); } mHttpClient = new OkHttpClient(); }
From source file:com.heske.alexandria.api.AlexandriaApplication.java
License:Apache License
private void setupRestAdapter() { OkHttpClient client = new OkHttpClient(); HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); client.interceptors().add(interceptor); mRetrofit = new Retrofit.Builder().baseUrl("https://www.googleapis.com/books/") .addConverterFactory(JacksonConverterFactory.create()).client(client).build(); mApiService = mRetrofit.create(BookApiService.class); }
From source file:com.ibm.watson.developer_cloud.service.WatsonService.java
License:Open Source License
/** * Configures the HTTP client.//from ww w . j a va2 s.c o m * * @return the HTTP client */ protected OkHttpClient configureHttpClient() { final OkHttpClient client = new OkHttpClient(); final CookieManager cookieManager = new CookieManager(); cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL); client.setCookieHandler(cookieManager); client.setConnectTimeout(60, TimeUnit.SECONDS); client.setWriteTimeout(60, TimeUnit.SECONDS); client.setReadTimeout(90, TimeUnit.SECONDS); return client; }