List of usage examples for org.apache.http.params CoreProtocolPNames USE_EXPECT_CONTINUE
String USE_EXPECT_CONTINUE
To view the source code for org.apache.http.params CoreProtocolPNames USE_EXPECT_CONTINUE.
Click Source Link
From source file:website.openeng.libanki.sync.HttpSyncer.java
public HttpResponse req(String method, InputStream fobj, int comp, JSONObject registerData, Connection.CancelCallback cancelCallback) throws UnknownHttpResponseException { File tmpFileBuffer = null;/*from w w w.j av a 2s.c om*/ try { String bdry = "--" + BOUNDARY; StringWriter buf = new StringWriter(); // post vars mPostVars.put("c", comp != 0 ? 1 : 0); for (String key : mPostVars.keySet()) { buf.write(bdry + "\r\n"); buf.write(String.format(Locale.US, "Content-Disposition: form-data; name=\"%s\"\r\n\r\n%s\r\n", key, mPostVars.get(key))); } tmpFileBuffer = File.createTempFile("syncer", ".tmp", new File(KanjiDroidApp.getCacheStorageDirectory())); FileOutputStream fos = new FileOutputStream(tmpFileBuffer); BufferedOutputStream bos = new BufferedOutputStream(fos); GZIPOutputStream tgt; // payload as raw data or json if (fobj != null) { // header buf.write(bdry + "\r\n"); buf.write( "Content-Disposition: form-data; name=\"data\"; filename=\"data\"\r\nContent-Type: application/octet-stream\r\n\r\n"); buf.close(); bos.write(buf.toString().getBytes("UTF-8")); // write file into buffer, optionally compressing int len; BufferedInputStream bfobj = new BufferedInputStream(fobj); byte[] chunk = new byte[65536]; if (comp != 0) { tgt = new GZIPOutputStream(bos); while ((len = bfobj.read(chunk)) >= 0) { tgt.write(chunk, 0, len); } tgt.close(); bos = new BufferedOutputStream(new FileOutputStream(tmpFileBuffer, true)); } else { while ((len = bfobj.read(chunk)) >= 0) { bos.write(chunk, 0, len); } } bos.write(("\r\n" + bdry + "--\r\n").getBytes("UTF-8")); } else { buf.close(); bos.write(buf.toString().getBytes("UTF-8")); } bos.flush(); bos.close(); // connection headers String url = Consts.SYNC_BASE; if (method.equals("register")) { url = url + "account/signup" + "?username=" + registerData.getString("u") + "&password=" + registerData.getString("p"); } else if (method.startsWith("upgrade")) { url = url + method; } else { url = syncURL() + method; } HttpPost httpPost = new HttpPost(url); HttpEntity entity = new ProgressByteEntity(tmpFileBuffer); // body httpPost.setEntity(entity); httpPost.setHeader("Content-type", "multipart/form-data; boundary=" + BOUNDARY); // HttpParams HttpParams params = new BasicHttpParams(); params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30); params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30)); params.setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false); params.setParameter(CoreProtocolPNames.USER_AGENT, "KanjiDroid-" + VersionUtils.getPkgVersionName()); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpConnectionParams.setSoTimeout(params, Connection.CONN_TIMEOUT); // Registry SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", new EasySSLSocketFactory(), 443)); ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, registry); if (cancelCallback != null) { cancelCallback.setConnectionManager(cm); } try { HttpClient httpClient = new DefaultHttpClient(cm, params); HttpResponse httpResponse = httpClient.execute(httpPost); // we assume badAuthRaises flag from Anki Desktop always False // so just throw new RuntimeException if response code not 200 or 403 assertOk(httpResponse); return httpResponse; } catch (SSLException e) { Timber.e(e, "SSLException while building HttpClient"); throw new RuntimeException("SSLException while building HttpClient"); } } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (IOException e) { Timber.e(e, "BasicHttpSyncer.sync: IOException"); throw new RuntimeException(e); } catch (JSONException e) { throw new RuntimeException(e); } finally { if (tmpFileBuffer != null && tmpFileBuffer.exists()) { tmpFileBuffer.delete(); } } }
From source file:com.cloverstudio.spikademo.couchdb.ConnectionHandler.java
/** * Forming a GET request//from w w w. java2 s . c o m * * @param url * @return * @throws ClientProtocolException * @throws IOException */ public static InputStream httpGetRequest(String url, String userId) throws ClientProtocolException, IOException { HttpGet httpget = new HttpGet(url); httpget.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false); httpget.setHeader("Content-Type", "application/json"); httpget.setHeader("Encoding", "utf-8"); httpget.setHeader("database", Const.DATABASE); if (userId != null && userId.length() > 0) httpget.setHeader("user_id", userId); else { String userIdSaved = SpikaApp.getPreferences().getUserId(); if (userIdSaved != null) httpget.setHeader("user_id", userIdSaved); } String token = SpikaApp.getPreferences().getUserToken(); if (token != null && token.length() > 0) httpget.setHeader("token", token); Logger.error("httpGetRequest", SpikaApp.getPreferences().getUserToken()); HttpResponse response = HttpSingleton.getInstance().execute(httpget); HttpEntity entity = response.getEntity(); return entity.getContent(); }
From source file:com.uf.togathor.db.couchdb.ConnectionHandler.java
/** * Forming a GET request/*ww w. ja v a2 s . co m*/ * * @param url * @return * @throws ClientProtocolException * @throws IOException * @throws JSONException * @throws IllegalStateException * @throws TogathorForbiddenException */ public static InputStream httpGetRequest(String url, String userId) throws IOException, TogathorException, IllegalStateException, JSONException, TogathorForbiddenException { HttpGet httpget = new HttpGet(url); httpget.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false); httpget.setHeader("Content-Type", "application/json"); httpget.setHeader("Encoding", "utf-8"); httpget.setHeader("database", Const.DATABASE); if (userId != null && userId.length() > 0) httpget.setHeader("user_id", userId); else { String userIdSaved = Togathor.getPreferences().getUserId(); if (userIdSaved != null) httpget.setHeader("user_id", userIdSaved); } String token = Togathor.getPreferences().getUserToken(); if (token != null && token.length() > 0) httpget.setHeader("token", token); Logger.error("httpGetRequest", Togathor.getPreferences().getUserToken()); print(httpget); HttpResponse response = HttpSingleton.getInstance().execute(httpget); HttpEntity entity = response.getEntity(); Logger.debug("STATUS", "" + response.getStatusLine().getStatusCode()); if (response.getStatusLine().getStatusCode() > 400) { HttpSingleton.sInstance = null; if (response.getStatusLine().getStatusCode() == 500) throw new TogathorException(getError(entity.getContent())); if (response.getStatusLine().getStatusCode() == 403) throw new TogathorForbiddenException(); throw new IOException(response.getStatusLine().getReasonPhrase()); } return entity.getContent(); }
From source file:net.vexelon.mobileops.GLBClient.java
/** * Initialize Http Client/*w w w. j ava2 s. c om*/ */ private void initHttpClient() { HttpParams params = new BasicHttpParams(); params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); params.setParameter(CoreProtocolPNames.USER_AGENT, UserAgentHelper.getRandomUserAgent()); //params.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, HTTP.UTF_8); // Bugfix #1: The target server failed to respond params.setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE); DefaultHttpClient client = new DefaultHttpClient(params); httpCookieStore = new BasicCookieStore(); client.setCookieStore(httpCookieStore); httpContext = new BasicHttpContext(); httpContext.setAttribute(ClientContext.COOKIE_STORE, httpCookieStore); // Bugfix #1: Adding retry handler to repeat failed requests HttpRequestRetryHandler retryHandler = new HttpRequestRetryHandler() { @Override public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount >= MAX_REQUEST_RETRIES) { return false; } if (exception instanceof NoHttpResponseException || exception instanceof ClientProtocolException) { return true; } return false; } }; client.setHttpRequestRetryHandler(retryHandler); // SSL HostnameVerifier verifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; try { SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", new PlainSocketFactory(), 80)); registry.register(new Scheme("https", new TrustAllSocketFactory(), 443)); SingleClientConnManager connMgr = new SingleClientConnManager(client.getParams(), registry); httpClient = new DefaultHttpClient(connMgr, client.getParams()); } catch (InvalidAlgorithmParameterException e) { // Log.e(Defs.LOG_TAG, "", e); // init without connection manager httpClient = new DefaultHttpClient(client.getParams()); } HttpsURLConnection.setDefaultHostnameVerifier(verifier); }
From source file:com.expertiseandroid.lib.sociallib.utils.Utils.java
/** * Posts a photo to twitpic/*from w w w . ja va2 s. co m*/ * @param attachment the picture * @param consumer the Oauth consumer * @param tpKey the twitpic key * @param message a caption associated with the picture * @return the server's response * @throws OAuthMessageSignerException * @throws OAuthExpectationFailedException * @throws OAuthCommunicationException * @throws UnsupportedEncodingException * @throws IOException */ public static ReadableResponse postTwitpic(Bitmap attachment, CommonsHttpOAuthConsumer consumer, String tpKey, String message) throws OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException, UnsupportedEncodingException, IOException { String boundary = generateBoundaryString(20); HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(TWITPIC_UPLOAD); post.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false); post.addHeader(OAUTH_ECHO_AUTH, getVerifyCredentialsAuthString(consumer)); post.addHeader(X_AUTH_SERVICE_PROVIDER, TWITTER_VERIFY_CREDENTIALS); post.addHeader("Content-Type", "multipart/form-data; boundary=" + boundary); Map<String, String> params = new HashMap<String, String>(); params.put("key", tpKey); params.put("message", message); byte[] body = generatePostBody2(params, attachment, boundary); post.setEntity(new ByteArrayEntity(body)); return new HttpResponseWrapper(client.execute(post)); }
From source file:org.openiot.gsn.http.rest.PushRemoteWrapper.java
public void run() { HttpPost httpPost = new HttpPost(initParams.getRemoteContactPointEncoded(lastReceivedTimestamp)); ///*from w w w. j a va2 s. c o m*/ httpPost.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE); // HttpResponse response = null; //This is acting as keep alive. // while (isActive()) { try { Thread.sleep(KEEP_ALIVE_PERIOD); httpPost.setEntity(new UrlEncodedFormEntity(postParameters, HTTP.UTF_8)); response = null; response = httpclient.execute(httpPost); int status = response.getStatusLine().getStatusCode(); if (status != RestStreamHanlder.SUCCESS_200) { logger.error("Cant register to the remote client, retrying in:" + (KEEP_ALIVE_PERIOD / 1000) + " seconds."); structure = registerAndGetStructure(); } } catch (Exception e) { logger.warn(e.getMessage(), e); } finally { if (response != null) { try { response.getEntity().getContent().close(); } catch (Exception e) { logger.warn(e.getMessage(), e); } } } } }
From source file:com.cloverstudio.spikademo.couchdb.ConnectionHandler.java
/** * Forming a POST request/*from ww w . j a v a2 s. c o m*/ * * @param url * @param create * @return * @throws ClientProtocolException * @throws IOException */ private static InputStream httpPostRequest(String url, Object create, String userId) throws ClientProtocolException, IOException { HttpPost httppost = new HttpPost(url); httppost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false); httppost.setHeader("Content-Type", "application/json"); httppost.setHeader("Encoding", "utf-8"); httppost.setHeader("database", Const.DATABASE); if (userId != null && userId.length() > 0) httppost.setHeader("user_id", userId); else { String userIdSaved = SpikaApp.getPreferences().getUserId(); if (userIdSaved != null) httppost.setHeader("user_id", userIdSaved); } String token = SpikaApp.getPreferences().getUserToken(); if (token != null && token.length() > 0) httppost.setHeader("token", token); StringEntity stringEntity = new StringEntity(create.toString(), HTTP.UTF_8); httppost.setEntity(stringEntity); HttpResponse response = HttpSingleton.getInstance().execute(httppost); HttpEntity entity = response.getEntity(); return entity.getContent(); }
From source file:org.apache.camel.component.social.providers.twitter.AbstractTwitterPath.java
protected HttpResponse callHttpMethod(Map<String, Object> params, HttpUriRequest method) throws SocialDataFetchError { method.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false); List<NameValuePair> postMethod = new ArrayList<NameValuePair>(); for (Map.Entry<String, Object> e : params.entrySet()) { if (method instanceof HttpEntityEnclosingRequestBase) { postMethod.add(new BasicNameValuePair(e.getKey(), e.getValue().toString())); } else {// ww w . j av a2 s . c o m method.getParams().setParameter(e.getKey(), e.getValue()); } } if (method instanceof HttpEntityEnclosingRequestBase) { try { ((HttpEntityEnclosingRequestBase) method) .setEntity(new UrlEncodedFormEntity(postMethod, HTTP.UTF_8)); } catch (UnsupportedEncodingException e1) { } } HttpResponse response; try { response = httpClient.execute(method); } catch (Exception e) { throw new SocialDataFetchError(e); } return response; }
From source file:com.uf.togathor.db.couchdb.ConnectionHandler.java
/** * Forming a POST request//from www .j a va 2s. co m * * @param url * @param create * @return * @throws ClientProtocolException * @throws IOException * @throws TogathorException * @throws IllegalStateException * @throws JSONException * @throws TogathorForbiddenException */ private static InputStream httpPostRequest(String url, Object create, String userId) throws IOException, IllegalStateException, TogathorException, JSONException, TogathorForbiddenException { HttpPost httppost = new HttpPost(url); httppost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false); HttpConnectionParams.setConnectionTimeout(httppost.getParams(), 5000); HttpConnectionParams.setSoTimeout(httppost.getParams(), 5000); Logger.debug("TIMEOUTS", HttpConnectionParams.getConnectionTimeout(httppost.getParams()) + " " + HttpConnectionParams.getSoTimeout(httppost.getParams())); httppost.setHeader("Content-Type", "application/json"); httppost.setHeader("Encoding", "utf-8"); httppost.setHeader("database", Const.DATABASE); if (userId != null && userId.length() > 0) httppost.setHeader("user_id", userId); else { String userIdSaved = Togathor.getPreferences().getUserId(); if (userIdSaved != null) httppost.setHeader("user_id", userIdSaved); } String token = Togathor.getPreferences().getUserToken(); if (token != null && token.length() > 0) httppost.setHeader("token", token); StringEntity stringEntity = new StringEntity(create.toString(), HTTP.UTF_8); httppost.setEntity(stringEntity); print(httppost); HttpResponse response = HttpSingleton.getInstance().execute(httppost); HttpEntity entity = response.getEntity(); Logger.debug("STATUS", "" + response.getStatusLine().getStatusCode()); if (response.getStatusLine().getStatusCode() > 400) { HttpSingleton.sInstance = null; if (response.getStatusLine().getStatusCode() == 500) throw new TogathorException(getError(entity.getContent())); if (response.getStatusLine().getStatusCode() == 403) throw new TogathorForbiddenException(); throw new IOException(response.getStatusLine().getReasonPhrase()); } return entity.getContent(); }