List of usage examples for org.apache.http.client HttpClient getParams
@Deprecated HttpParams getParams();
From source file:com.autburst.picture.server.HttpRequest.java
public void post(String url, File file) throws Exception { HttpClient httpClient = new DefaultHttpClient(); try {/*from ww w . ja va2 s . com*/ httpClient.getParams().setParameter("http.socket.timeout", new Integer(90000)); // 90 sec. HttpPost post = new HttpPost(url); // Multi mpEntity = new MultipartEntity(); // ContentBody cbFile = new FileBody(file, "image/jpeg"); // mpEntity.addPart("userfile", cbFile); FileEntity entity; // entity = new FileEntity(file, "binary/octet-stream"); entity = new FileEntity(file, "image/jpeg"); //entity.setChunked(true); post.setEntity(entity); //post.setHeader("Content-type", "image/jpeg"); // Send any XML file as the body of the POST request // File f = new File("students.xml"); // System.out.println("File Length = " + f.length()); // post.setBody(new FileInputStream(file)); //// c //// "image/jpeg; charset=ISO-8859-1"); // post.setHeader("Content-type", "image/jpeg"); post.addHeader("filename", file.getName()); HttpResponse response = httpClient.execute(post); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_NO_CONTENT) { Log.e(TAG, "--------Error--------Response Status linecode:" + response.getStatusLine()); throw new Exception("--------Error--------Response Status linecode:" + response.getStatusLine()); } // else { // // Here every thing is fine. // } // HttpEntity resEntity = response.getEntity(); // if (resEntity == null) { // Log.e(TAG, "---------Error No Response !!!-----"); // } } catch (Exception ex) { Log.e(TAG, "---------Error-----" + ex.getMessage()); throw new Exception(ex); } finally { httpClient.getConnectionManager().shutdown(); } }
From source file:uk.co.unclealex.googleauth.ApacheHttpTransport.java
/** * Constructor that allows an alternative Apache HTTP client to be used. * * <p>//from ww w . j a v a2 s.c o m * Note that a few settings are overridden: * </p> * <ul> * <li>HTTP version is set to 1.1 using {@link HttpProtocolParams#setVersion} with * {@link HttpVersion#HTTP_1_1}.</li> * <li>Redirects are disabled using {@link ClientPNames#HANDLE_REDIRECTS}.</li> * <li>{@link ConnManagerParams#setTimeout} and {@link HttpConnectionParams#setConnectionTimeout} * are set on each request based on {@link HttpRequest#getConnectTimeout()}.</li> * <li>{@link HttpConnectionParams#setSoTimeout} is set on each request based on * {@link HttpRequest#getReadTimeout()}.</li> * </ul> * * @param httpClient Apache HTTP client to use * * @since 1.6 */ public ApacheHttpTransport(HttpClient httpClient, int port) { this.httpClient = httpClient; this.port = port; HttpParams params = httpClient.getParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false); }
From source file:net.sourceforge.subsonic.controller.MultiController.java
private boolean emailPassword(String password, String username, String email) { HttpClient client = new DefaultHttpClient(); try {/*from w w w. j a va2s . co m*/ HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); HttpConnectionParams.setSoTimeout(client.getParams(), 10000); HttpPost method = new HttpPost("http://subsonic.org/backend/sendMail.view"); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("from", "noreply@subsonic.org")); params.add(new BasicNameValuePair("to", email)); params.add(new BasicNameValuePair("subject", "Subsonic Password")); params.add(new BasicNameValuePair("text", "Hi there!\n\n" + "You have requested to reset your Subsonic password. Please find your new login details below.\n\n" + "Username: " + username + "\n" + "Password: " + password + "\n\n" + "--\n" + "The Subsonic Team\n" + "subsonic.org")); method.setEntity(new UrlEncodedFormEntity(params, StringUtil.ENCODING_UTF8)); client.execute(method); return true; } catch (Exception x) { LOG.warn("Failed to send email.", x); return false; } finally { client.getConnectionManager().shutdown(); } }
From source file:com.eastedge.readnovel.weibo.net.Utility.java
/** * Get a HttpClient object which is setting correctly . * //w ww . j a v a 2s .c o m * @param context * : context of activity * @return HttpClient: HttpClient object */ public static HttpClient getHttpClient(Context context) { BasicHttpParams httpParameters = new BasicHttpParams(); // Set the default socket timeout (SO_TIMEOUT) // in // milliseconds which is the timeout for waiting for data. HttpConnectionParams.setConnectionTimeout(httpParameters, Utility.SET_CONNECTION_TIMEOUT); HttpConnectionParams.setSoTimeout(httpParameters, Utility.SET_SOCKET_TIMEOUT); HttpClient client = new DefaultHttpClient(httpParameters); WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); if (!wifiManager.isWifiEnabled()) { Uri uri = Uri.parse("content://telephony/carriers/preferapn"); Cursor mCursor = context.getContentResolver().query(uri, null, null, null, null); if (mCursor != null && mCursor.moveToFirst()) { String proxyStr = mCursor.getString(mCursor.getColumnIndex("proxy")); if (proxyStr != null && proxyStr.trim().length() > 0) { HttpHost proxy = new HttpHost(proxyStr, 80); client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy); } mCursor.close(); } } return client; }
From source file:helper.util.RESTClient.java
/** * Main method for server request. Depending on call status, the callback methods are * invoked./* w w w . ja va2 s. c o m*/ * @param URI full address from which we need to get response. */ @Override protected Void doInBackground(URI... uris) { if (!networkAvailable()) { System.out.println("no network connection"); _handler.onFailure(FailStatus.NoNetworkConnection); return null; } HttpClient httpclient = new DefaultHttpClient(); final HttpParams httpParameters = httpclient.getParams(); int connectionTimeOutSec = 10; HttpConnectionParams.setConnectionTimeout(httpParameters, connectionTimeOutSec * 1000); int socketTimeoutSec = 10; HttpConnectionParams.setSoTimeout(httpParameters, socketTimeoutSec * 1000); HttpRequestBase httpRequest = null; if (_methodType == "GET") { // check if we have any params if (_params != null) { String paramString = URLEncodedUtils.format(_params, "utf-8"); httpRequest = new HttpGet(uris[0] + "?" + paramString); Log.d("request", uris[0] + "?" + paramString); } else { httpRequest = new HttpGet(uris[0]); Log.d("request", uris[0].toString()); } } else { httpRequest = new HttpPost(uris[0]); if (_params != null) { Log.d("request", uris[0].toString()); addPostParameters(httpRequest); } } httpRequest.setHeader("Accept", "application/json"); httpRequest.setHeader("Content-Type", "application/json"); try { // start http request HttpResponse response = httpclient.execute(httpRequest); // get response string String responseData = EntityUtils.toString(response.getEntity(), HTTP.UTF_8); // determine response type(json array or object) Object json = null; try { json = new JSONTokener(responseData).nextValue(); _handler.onSuccess(json); } catch (JSONException e) { _handler.onFailure(FailStatus.JSONException); } } catch (ClientProtocolException e) { System.out.println("AsyncTask:GetUserDataThread:ClientProtocolException: " + e.getMessage()); _handler.onFailure(FailStatus.ClientProtocolException); } catch (IOException e) { System.out.println("AsyncTask:GetUserDataThread:IOException: " + e.getMessage()); _handler.onFailure(FailStatus.IOException); } return null; }
From source file:org.dspace.submit.lookup.PubmedService.java
public List<Record> getByPubmedIDs(List<String> pubmedIDs) throws HttpException, IOException, ParserConfigurationException, SAXException { List<Record> results = new ArrayList<Record>(); HttpGet method = null;//www .j a v a 2 s.co m try { HttpClient client = new DefaultHttpClient(); client.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5 * timeout); try { URIBuilder uriBuilder = new URIBuilder("http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi"); uriBuilder.addParameter("db", "pubmed"); uriBuilder.addParameter("retmode", "xml"); uriBuilder.addParameter("rettype", "full"); uriBuilder.addParameter("id", StringUtils.join(pubmedIDs.iterator(), ",")); method = new HttpGet(uriBuilder.build()); } catch (URISyntaxException ex) { throw new RuntimeException("Request not sent", ex); } // Execute the method. HttpResponse response = client.execute(method); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode != HttpStatus.SC_OK) { throw new RuntimeException("WS call failed: " + statusLine); } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setIgnoringComments(true); factory.setIgnoringElementContentWhitespace(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document inDoc = builder.parse(response.getEntity().getContent()); Element xmlRoot = inDoc.getDocumentElement(); List<Element> pubArticles = XMLUtils.getElementList(xmlRoot, "PubmedArticle"); for (Element xmlArticle : pubArticles) { Record pubmedItem = null; try { pubmedItem = PubmedUtils.convertPubmedDomToRecord(xmlArticle); results.add(pubmedItem); } catch (Exception e) { throw new RuntimeException("PubmedID is not valid or not exist: " + e.getMessage(), e); } } return results; } finally { if (method != null) { method.releaseConnection(); } } }
From source file:com.gitblit.plugin.glip.Glip.java
/** * Send a payload message./*from w w w .j a v a2 s .c om*/ * * @param payload * @throws IOException */ public void send(Payload payload) throws IOException { String conversation = payload.getConversation(); String token; if (StringUtils.isEmpty(conversation)) { // default conversation token = runtimeManager.getSettings().getString(Plugin.SETTING_DEFAULT_TOKEN, null); } else { // specified conversation, validate token token = runtimeManager.getSettings() .getString(String.format(Plugin.SETTING_CONVERSATION_TOKEN, conversation), null); if (StringUtils.isEmpty(token)) { token = runtimeManager.getSettings().getString(Plugin.SETTING_DEFAULT_TOKEN, null); log.warn("No Glip API token specified for '{}', defaulting to default conversation'", payload.getConversation()); log.warn("Please set '{} = TOKEN' in gitblit.properties", String.format(Plugin.SETTING_CONVERSATION_TOKEN, conversation)); } } Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new GmtDateTypeAdapter()).create(); String json = gson.toJson(payload); log.debug(json); HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(AllClientPNames.CONNECTION_TIMEOUT, 5000); client.getParams().setParameter(AllClientPNames.SO_TIMEOUT, 5000); String conversationUrl = payload.getEndPoint(token); HttpPost post = new HttpPost(conversationUrl); post.getParams().setParameter(CoreProtocolPNames.USER_AGENT, Constants.NAME + "/" + Constants.getVersion()); post.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8"); // post as JSON StringEntity entity = new StringEntity(json, "UTF-8"); entity.setContentType("application/json"); post.setEntity(entity); HttpResponse response = client.execute(post); int rc = response.getStatusLine().getStatusCode(); if (HttpStatus.SC_OK == rc) { // This is the expected result code // replace this with post.closeConnection() after JGit updates to HttpClient 4.2 post.abort(); } else { String result = null; InputStream is = response.getEntity().getContent(); try { byte[] buffer = new byte[8192]; ByteArrayOutputStream os = new ByteArrayOutputStream(); int len = 0; while ((len = is.read(buffer)) > -1) { os.write(buffer, 0, len); } result = os.toString("UTF-8"); } finally { if (is != null) { is.close(); } } log.error("Glip plugin sent:"); log.error(json); log.error("Glip returned:"); log.error(result); throw new IOException(String.format("Glip Error (%s): %s", rc, result)); } }
From source file:org.eclipse.skalli.model.ext.maven.internal.HttpMavenPomResolverBase.java
/** * @param logResponse = true will return an default empty MavenPom and log the content read from the * url with level Error to LOG; if set to false the method parse is called. *//*ww w. j a va 2 s.c o m*/ private MavenPom parse(URL url, String relativePath, boolean logResponse) throws IOException, HttpException, ValidationException { HttpClient client = Destinations.getClient(url); if (client == null) { return null; } HttpParams params = client.getParams(); HttpClientParams.setRedirecting(params, false); // we want to find 301 MOVED PERMANTENTLY HttpResponse response = null; try { LOG.info("GET " + url); //$NON-NLS-1$ HttpGet method = new HttpGet(url.toExternalForm()); response = client.execute(method); int status = response.getStatusLine().getStatusCode(); LOG.info(status + " " + response.getStatusLine().getReasonPhrase()); //$NON-NLS-1$ if (status == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); if (entity == null) { return null; } if (!logResponse) { return parse(asPomInputStream(entity, relativePath)); } else { logResponse(url, entity); return new MavenPom(); } } else { String statusText = response.getStatusLine().getReasonPhrase(); switch (status) { case SC_NOT_FOUND: throw new HttpException(MessageFormat.format("{0} not found", url)); case SC_UNAUTHORIZED: throw new HttpException(MessageFormat.format("{0} found but authentication required: {1} {2}", url, status, statusText)); case SC_INTERNAL_SERVER_ERROR: case SC_SERVICE_UNAVAILABLE: case SC_GATEWAY_TIMEOUT: case SC_INSUFFICIENT_STORAGE: throw new HttpException(MessageFormat.format( "{0} not found. Host reports a temporary problem: {1} {2}", url, status, statusText)); case SC_MOVED_PERMANENTLY: throw new HttpException( MessageFormat.format("{0} not found. Resource has been moved permanently to {1}", url, response.getFirstHeader("Location"))); default: throw new HttpException(MessageFormat.format("{0} not found. Host responded with {1} {2}", url, status, statusText)); } } } finally { HttpUtils.consumeQuietly(response); } }
From source file:free.yhc.netmbuddy.model.NetLoader.java
private HttpClient newHttpClient(String proxyAddr) { if (isValidProxyAddr(proxyAddr)) { // TODO/*from w ww . j a va 2s . com*/ // Not supported yet. eAssert(false); return null; } HttpClient hc = new DefaultHttpClient(); HttpParams params = hc.getParams(); HttpConnectionParams.setConnectionTimeout(params, Policy.NETWORK_CONN_TIMEOUT); HttpConnectionParams.setSoTimeout(params, Policy.NETWORK_CONN_TIMEOUT); HttpProtocolParams.setUserAgent(hc.getParams(), Policy.HTTP_UASTRING); params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109); return hc; }
From source file:net.peterkuterna.android.apps.devoxxsched.c2dm.AppEngineRequestTransport.java
public void send(String payload, TransportReceiver receiver, boolean newToken) { Throwable ex;/*from w w w. jav a2 s. c o m*/ try { final SharedPreferences prefs = Prefs.get(context); final String accountName = prefs.getString(DevoxxPrefs.ACCOUNT_NAME, "unknown"); Account account = new Account(accountName, "com.google"); String authToken = getAuthToken(context, account); if (newToken) { // invalidate the cached token AccountManager accountManager = AccountManager.get(context); accountManager.invalidateAuthToken(account.type, authToken); authToken = getAuthToken(context, account); } HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, HttpUtils.buildUserAgent(context)); String continueURL = BASE_URL; URI uri = new URI( AUTH_URL + "?continue=" + URLEncoder.encode(continueURL, "UTF-8") + "&auth=" + authToken); HttpGet method = new HttpGet(uri); final HttpParams getParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(getParams, 20 * SECOND_IN_MILLIS); HttpConnectionParams.setSoTimeout(getParams, 20 * SECOND_IN_MILLIS); HttpClientParams.setRedirecting(getParams, false); method.setParams(getParams); HttpResponse res = client.execute(method); Header[] headers = res.getHeaders("Set-Cookie"); if (!newToken && (res.getStatusLine().getStatusCode() != 302 || headers.length == 0)) { send(payload, receiver, true); } String ascidCookie = null; for (Header header : headers) { if (header.getValue().indexOf("ACSID=") >= 0) { // let's parse it String value = header.getValue(); String[] pairs = value.split(";"); ascidCookie = pairs[0]; } } // Make POST request uri = new URI(BASE_URL + urlPath); HttpPost post = new HttpPost(); post.setHeader("Content-Type", "application/json;charset=UTF-8"); post.setHeader("Cookie", ascidCookie); post.setURI(uri); post.setEntity(new StringEntity(payload, "UTF-8")); HttpResponse response = client.execute(post); if (200 == response.getStatusLine().getStatusCode()) { String contents = readStreamAsString(response.getEntity().getContent()); receiver.onTransportSuccess(contents); } else { receiver.onTransportFailure(new ServerFailure(response.getStatusLine().getReasonPhrase())); } return; } catch (UnsupportedEncodingException e) { ex = e; } catch (ClientProtocolException e) { ex = e; } catch (IOException e) { ex = e; } catch (URISyntaxException e) { ex = e; } catch (PendingAuthException e) { final Intent intent = new Intent(SettingsActivity.AUTH_PERMISSION_ACTION); intent.putExtra("AccountManagerBundle", e.getAccountManagerBundle()); context.sendBroadcast(intent); return; } catch (Exception e) { ex = e; } receiver.onTransportFailure(new ServerFailure(ex.getMessage())); }