@Override public RequestHandle executeSample(final AsyncHttpClient client, final String URL, final Header[] headers, HttpEntity entity, final ResponseHandlerInterface responseHandler) { if (client instanceof SyncHttpClient) { new Thread(new Runnable() { @Override public void run() { Log.d(LOG_TAG, "Before Request"); client.get(SynchronousClientSample.this, URL, headers, null, responseHandler); Log.d(LOG_TAG, "After Request"); } }).start(); } else { Log.e(LOG_TAG, "Error, not using SyncHttpClient"); } /** * SyncHttpClient does not return RequestHandle, * it executes each request directly, * therefore those requests are not in cancelable threads * */ return null; }
@Override public RequestHandle executeSample(AsyncHttpClient client, String URL, Header[] headers, HttpEntity entity, ResponseHandlerInterface responseHandler) { RequestParams params = new RequestParams(); params.setUseJsonStreamer(true); JSONObject body; if (isRequestBodyAllowed() && (body = getBodyTextAsJSON()) != null) { try { Iterator keys = body.keys(); Log.d(LOG_TAG, "JSON data:"); while (keys.hasNext()) { String key = (String) keys.next(); Log.d(LOG_TAG, " " + key + ": " + body.get(key)); params.put(key, body.get(key).toString()); } } catch (JSONException e) { Log.w(LOG_TAG, "Unable to retrieve a JSON value", e); } } return client.post(this, URL, headers, params, RequestParams.APPLICATION_JSON, responseHandler); }
@Override public RequestHandle executeSample(final AsyncHttpClient client, final String URL, final Header[] headers, HttpEntity entity, final ResponseHandlerInterface responseHandler) { final Activity ctx = this; FutureTask<RequestHandle> future = new FutureTask<>(new Callable<RequestHandle>() { public RequestHandle call() { Log.d(LOG_TAG, "Executing GET request on background thread"); return client.get(ctx, URL, headers, null, responseHandler); } }); executor.execute(future); RequestHandle handle = null; try { handle = future.get(5, TimeUnit.SECONDS); Log.d(LOG_TAG, "Background thread for GET request has finished"); } catch (Exception e) { Toast.makeText(ctx, e.getMessage(), Toast.LENGTH_LONG).show(); e.printStackTrace(); } return handle; }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // The following exceptions will be whitelisted, i.e.: When an exception // of this type is raised, the request will be retried. AsyncHttpClient.allowRetryExceptionClass(IOException.class); AsyncHttpClient.allowRetryExceptionClass(SocketTimeoutException.class); AsyncHttpClient.allowRetryExceptionClass(ConnectTimeoutException.class); // The following exceptions will be blacklisted, i.e.: When an exception // of this type is raised, the request will not be retried and it will // fail immediately. AsyncHttpClient.blockRetryExceptionClass(UnknownHostException.class); AsyncHttpClient.blockRetryExceptionClass(ConnectionPoolTimeoutException.class); }
@Override public RequestHandle executeSample(AsyncHttpClient client, String URL, Header[] headers, HttpEntity entity, ResponseHandlerInterface responseHandler) { try { RequestParams params = new RequestParams(); final String contentType = RequestParams.APPLICATION_OCTET_STREAM; params.put("fileOne", createTempFile("fileOne", 1020), contentType, "fileOne"); params.put("fileTwo", createTempFile("fileTwo", 1030), contentType); params.put("fileThree", createTempFile("fileThree", 1040), contentType, "customFileThree"); params.put("fileFour", createTempFile("fileFour", 1050), contentType); params.put("fileFive", createTempFile("fileFive", 1060), contentType, "testingFileFive"); params.setHttpEntityIsRepeatable(true); params.setUseJsonStreamer(false); return client.post(this, URL, params, responseHandler); } catch (FileNotFoundException fnfException) { Log.e(LOG_TAG, "executeSample failed with FileNotFoundException", fnfException); } return null; }
private static boolean b(HttpUriRequest httpUriRequest) { Header[] headers = httpUriRequest.getHeaders("content-encoding"); if (headers != null) { for (Header value : headers) { if (AsyncHttpClient.ENCODING_GZIP.equalsIgnoreCase(value.getValue())) { return true; } } } Header[] headers2 = httpUriRequest.getHeaders(d.d); if (headers2 == null) { return true; } for (Header header : headers2) { for (String startsWith : b) { if (header.getValue().startsWith(startsWith)) { return false; } } } return true; }
private HttpUriRequest c() { if (this.f != null) { return this.f; } if (this.j == null) { byte[] b = this.c.b(); CharSequence b2 = this.c.b(AsyncHttpClient.ENCODING_GZIP); if (b != null) { if (TextUtils.equals(b2, "true")) { this.j = b.a(b); } else { this.j = new ByteArrayEntity(b); } this.j.setContentType(this.c.c()); } } HttpEntity httpEntity = this.j; if (httpEntity != null) { HttpUriRequest httpPost = new HttpPost(b()); httpPost.setEntity(httpEntity); this.f = httpPost; } else { this.f = new HttpGet(b()); } return this.f; }
public void Register(View v){ HttpClientHelper helper=new HttpClientHelper(new AsyncHttpClient()); final EditText name=(EditText)findViewById(R.id.name); final EditText email=(EditText)findViewById(R.id.email); final EditText pw=(EditText)findViewById(R.id.pw); final EditText pwc=(EditText)findViewById(R.id.pwc); if(pw.getText().toString().equals(pwc.getText().toString())) { helper.postRegister(name.getText().toString(), email.getText().toString(), pw.getText().toString(),this); } else { Toast.makeText(this, "Passwords are different", Toast.LENGTH_SHORT).show(); } }
private void setBingImg() { AsyncHttpClient client = new AsyncHttpClient(); client.get("https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1", new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { if (statusCode == 200) { Gson gson = new Gson(); BingImage bingImage = gson.fromJson(response.toString(), BingImage.class); List<BingImage.ImagesBean> img = bingImage.getImages(); if (img != null && img.size() > 0) { backImgUrl = "https://cn.bing.com" + img.get(0).getUrl(); setBackgroundImage(); } else Log.d("main", "onSuccess: 没有获取到类型"); } } } ); }
public static void setHttpClient(AsyncHttpClient c, Application application) { c.addHeader("Accept-Language", Locale.getDefault().toString()); c.addHeader("Host", HOST); c.addHeader("Connection", "Keep-Alive"); //noinspection deprecation c.getHttpClient().getParams() .setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true); // Set AppToken c.addHeader("AppToken", Verifier.getPrivateToken(application)); //c.addHeader("AppToken", "123456"); // setUserAgent c.setUserAgent(ApiClientHelper.getUserAgent(AppContext.getInstance())); CLIENT = c; initSSL(CLIENT); initSSL(API.mClient); }
public static void cleanCookie() { // first clear store // new PersistentCookieStore(AppContext.getInstance()).clear(); // clear header AsyncHttpClient client = CLIENT; if (client != null) { HttpContext httpContext = client.getHttpContext(); CookieStore cookies = (CookieStore) httpContext .getAttribute(HttpClientContext.COOKIE_STORE); // 清理Async本地存储 if (cookies != null) { cookies.clear(); } // 清理当前正在使用的Cookie client.removeHeader("Cookie"); } log("cleanCookie"); }
/** * 从AsyncHttpClient自带缓存中获取CookieString * * @param client AsyncHttpClient * @return CookieString */ private static String getClientCookie(AsyncHttpClient client) { String cookie = ""; if (client != null) { HttpContext httpContext = client.getHttpContext(); CookieStore cookies = (CookieStore) httpContext .getAttribute(HttpClientContext.COOKIE_STORE); if (cookies != null && cookies.getCookies() != null && cookies.getCookies().size() > 0) { for (Cookie c : cookies.getCookies()) { cookie += (c.getName() + "=" + c.getValue()) + ";"; } } } log("getClientCookie:" + cookie); return cookie; }
private static void initSSL(AsyncHttpClient client) { try { /// We initialize a default Keystore KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); // We load the KeyStore trustStore.load(null, null); // We initialize a new SSLSocketFacrory MySSLSocketFactory socketFactory = new MySSLSocketFactory(trustStore); // We set that all host names are allowed in the socket factory socketFactory.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); // We set the SSL Factory client.setSSLSocketFactory(socketFactory); // We initialize a GET http request } catch (Exception e) { e.printStackTrace(); } }
private Request networkRequest(Request request) throws IOException { Request.Builder result = request.newBuilder(); if (request.header("Host") == null) { result.header("Host", Util.hostHeader(request.httpUrl())); } if (request.header("Connection") == null) { result.header("Connection", "Keep-Alive"); } if (request.header(AsyncHttpClient.HEADER_ACCEPT_ENCODING) == null) { this.transparentGzip = true; result.header(AsyncHttpClient.HEADER_ACCEPT_ENCODING, AsyncHttpClient.ENCODING_GZIP); } CookieHandler cookieHandler = this.client.getCookieHandler(); if (cookieHandler != null) { OkHeaders.addCookies(result, cookieHandler.get(request.uri(), OkHeaders.toMultimap (result.build().headers(), null))); } if (request.header(Network.USER_AGENT) == null) { result.header(Network.USER_AGENT, Version.userAgent()); } return result.build(); }
public InputStream b() { if (d() < 400) { try { InputStream inputStream = a().getInputStream(); } catch (IOException e) { throw new RestException(e); } } inputStream = a().getErrorStream(); if (inputStream == null) { try { inputStream = a().getInputStream(); } catch (IOException e2) { throw new RestException(e2); } } if (!this.g || !AsyncHttpClient.ENCODING_GZIP.equals(c())) { return inputStream; } try { return new GZIPInputStream(inputStream); } catch (IOException e22) { throw new RestException(e22); } }
@Override public RequestHandle executeSample(AsyncHttpClient client, String URL, Header[] headers, HttpEntity entity, ResponseHandlerInterface responseHandler) { Intent serviceCall = new Intent(this, ExampleIntentService.class); serviceCall.putExtra(ExampleIntentService.INTENT_URL, URL); startService(serviceCall); return null; }
private void setCredentials(AsyncHttpClient client, String URL) { Uri parsed = Uri.parse(URL); client.clearCredentialsProvider(); client.setCredentials( new AuthScope(parsed.getHost(), parsed.getPort() == -1 ? 80 : parsed.getPort()), new UsernamePasswordCredentials( usernameField.getText().toString(), passwordField.getText().toString() ) ); }
public static InputStream a(HttpEntity httpEntity) { InputStream content = httpEntity.getContent(); if (content == null) { return content; } Header contentEncoding = httpEntity.getContentEncoding(); if (contentEncoding == null) { return content; } String value = contentEncoding.getValue(); if (value == null) { return content; } return value.contains(AsyncHttpClient.ENCODING_GZIP) ? new GZIPInputStream(content) : content; }
@Override public AsyncHttpClient getAsyncHttpClient() { AsyncHttpClient ahc = super.getAsyncHttpClient(); HttpClient client = ahc.getHttpClient(); if (client instanceof DefaultHttpClient) { Toast.makeText(this, String.format("redirects: %b\nrelative redirects: %b\ncircular redirects: %b", enableRedirects, enableRelativeRedirects, enableCircularRedirects), Toast.LENGTH_SHORT ).show(); ahc.setEnableRedirects(enableRedirects, enableRelativeRedirects, enableCircularRedirects); } return ahc; }
@Override public RequestHandle executeSample(AsyncHttpClient client, String URL, Header[] headers, HttpEntity entity, ResponseHandlerInterface responseHandler) { RequestParams rParams = new RequestParams(); rParams.put("sample_key", "Sample String"); try { File sample_file = File.createTempFile("temp_", "_handled", getCacheDir()); rParams.put("sample_file", sample_file); } catch (IOException e) { Log.e(LOG_TAG, "Cannot add sample file", e); } return client.post(this, URL, headers, rParams, "multipart/form-data", responseHandler); }
@Override public RequestHandle executeSample(AsyncHttpClient client, String URL, Header[] headers, HttpEntity entity, ResponseHandlerInterface responseHandler) { if (fileSize > 0) { // Send a GET query when we know the size of the remote file. return client.get(this, URL, headers, null, responseHandler); } else { // Send a HEAD query to know the size of the remote file. return client.head(this, URL, headers, null, responseHandler); } }
public static AbstractHttpEntity a(byte[] bArr) { if (((long) bArr.length) < a) { return new ByteArrayEntity(bArr); } OutputStream byteArrayOutputStream = new ByteArrayOutputStream(); OutputStream gZIPOutputStream = new GZIPOutputStream(byteArrayOutputStream); gZIPOutputStream.write(bArr); gZIPOutputStream.close(); AbstractHttpEntity byteArrayEntity = new ByteArrayEntity(byteArrayOutputStream.toByteArray()); byteArrayEntity.setContentEncoding(AsyncHttpClient.ENCODING_GZIP); new StringBuilder("gzip size:").append(bArr.length).append("->").append(byteArrayEntity.getContentLength()); return byteArrayEntity; }
private static AsyncHttpClient init() { AsyncHttpClient client = new AsyncHttpClient(); client.addHeader("Connection", "Keep-Alive"); client.setEnableRedirects(true, true, true); client.setTimeout(8 * 1000); return client; }
@Override public void onCreate() { super.onCreate(); pref=getSharedPreferences("update_data", MODE_PRIVATE); client=new AsyncHttpClient(); client.setTimeout(3000); client.setConnectTimeout(3000); client.setResponseTimeout(3000); }
public MyLoopjTask(Context context, OnLoopjCompleted listener) { asyncHttpClient = new AsyncHttpClient(); asyncHttpClient.setMaxRetriesAndTimeout(0, 1000); requestParams = new RequestParams(); this.context = context; this.loopjListener = listener; }
/** * @return an async client when calling from the main thread, otherwise a sync client. */ private static AsyncHttpClient getClient() { // Return the synchronous HTTP client when the thread is not prepared if (Looper.myLooper() == null) return syncHttpClient; return asyncHttpClient; }
/** * Attempts to encode response bytes as string of set encoding * * @param charset charset to create string with * @param stringBytes response bytes * @return String of set encoding or null */ public static String getResponseString(byte[] stringBytes, String charset) { try { String toReturn = (stringBytes == null) ? null : new String(stringBytes, charset); if (toReturn != null && toReturn.startsWith(UTF8_BOM)) { return toReturn.substring(1); } return toReturn; } catch (UnsupportedEncodingException e) { AsyncHttpClient.log.e(LOG_TAG, "Encoding response into string failed", e); return null; } }
/** * 初始化网络请求,包括Cookie的初始化 * * @param context AppContext */ public static void init(Application context) { API_URL = Setting.getServerUrl(context) + "%s"; AsyncHttpClient client = new ApiAsyncHttpClient(); client.setConnectTimeout(5 * 1000); client.setResponseTimeout(7 * 1000); //client.setCookieStore(new PersistentCookieStore(context)); // Set ApiHttpClient.setHttpClient(client, context); // Set Cookie setCookieHeader(AccountHelper.getCookie()); }
public void fill(IPreliminaryIndex preliminary, IProgressListener listener) throws SnapshotException, IOException { SimpleMonitor monitor = new SimpleMonitor(MessageUtil.format(Messages.HprofIndexBuilder_Parsing, this.file.getAbsolutePath()), listener, new int[]{500, AsyncHttpClient.DEFAULT_RETRY_SLEEP_TIME_MILLIS}); listener.beginTask(MessageUtil.format(Messages.HprofIndexBuilder_Parsing, this.file.getName()), (int) LocationClientOption.MIN_SCAN_SPAN_NETWORK); IHprofParserHandler handler = new HprofParserHandlerImpl(); handler.beforePass1(preliminary.getSnapshotInfo()); Listener mon = (Listener) monitor.nextMonitor(); mon.beginTask(MessageUtil.format(Messages.HprofIndexBuilder_Scanning, this.file.getAbsolutePath()), (int) (this.file.length() / 1000)); new Pass1Parser(handler, mon).read(this.file); if (listener.isCanceled()) { throw new OperationCanceledException(); } mon.done(); handler.beforePass2(listener); mon = (Listener) monitor.nextMonitor(); mon.beginTask(MessageUtil.format(Messages.HprofIndexBuilder_ExtractingObjects, this.file.getAbsolutePath()), (int) (this.file.length() / 1000)); new Pass2Parser(handler, mon).read(this.file); if (listener.isCanceled()) { throw new OperationCanceledException(); } mon.done(); if (listener.isCanceled()) { throw new OperationCanceledException(); } for (IParsingEnhancer enhancer : this.enhancers) { enhancer.onParsingCompleted(handler.getSnapshotInfo()); } this.id2position = handler.fillIn(preliminary); }
private Response unzip(Response response) throws IOException { if (!this.transparentGzip || !AsyncHttpClient.ENCODING_GZIP.equalsIgnoreCase(this .userResponse.header(AsyncHttpClient.HEADER_CONTENT_ENCODING)) || response.body() == null) { return response; } GzipSource responseBody = new GzipSource(response.body().source()); Headers strippedHeaders = response.headers().newBuilder().removeAll(AsyncHttpClient .HEADER_CONTENT_ENCODING).removeAll("Content-Length").build(); return response.newBuilder().headers(strippedHeaders).body(new RealResponseBody (strippedHeaders, Okio.buffer(responseBody))).build(); }
@Override public RequestHandle executeSample(AsyncHttpClient client, String URL, Header[] headers, HttpEntity entity, ResponseHandlerInterface responseHandler) { return client.delete(this, URL, headers, null, responseHandler); }