List of usage examples for org.apache.http.client HttpClient getParams
@Deprecated HttpParams getParams();
From source file:org.wso2.carbon.clustering.azure.AzureMembershipScheme.java
public InputStream getAPIresponse(String url, AuthenticationResult result) throws AzureMembershipSchemeException { InputStream instream = null;/*from ww w .j av a 2s . c o m*/ try { final HttpClient httpClient = new DefaultHttpClient(); HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), 10000); HttpGet httpGet = new HttpGet(url); httpGet.addHeader("Authorization", "Bearer " + result.getAccessToken()); HttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); instream = entity.getContent(); } catch (Exception ex) { throw new AzureMembershipSchemeException("Could not connect to Azure API", ex); } return instream; }
From source file:net.sourceforge.subsonic.backend.controller.RedirectionManagementController.java
public void test(HttpServletRequest request, HttpServletResponse response) throws Exception { String redirectFrom = StringUtils .lowerCase(ServletRequestUtils.getRequiredStringParameter(request, "redirectFrom")); PrintWriter writer = response.getWriter(); Redirection redirection = redirectionDao.getRedirection(redirectFrom); String webAddress = redirectFrom + ".subsonic.org"; if (redirection == null) { writer.print("Web address " + webAddress + " not registered."); return;// w ww .j a v a2s . c o m } if (redirection.getTrialExpires() != null && redirection.getTrialExpires().before(new Date())) { writer.print("Trial period expired. Please upgrade to Subsonic Premium to activate web address."); return; } String url = redirection.getRedirectTo(); if (!url.endsWith("/")) { url += "/"; } url += "index.html"; HttpClient client = new DefaultHttpClient(); HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000); HttpConnectionParams.setSoTimeout(client.getParams(), 15000); HttpGet method = new HttpGet(url); try { HttpResponse resp = client.execute(method); StatusLine status = resp.getStatusLine(); if (status.getStatusCode() == HttpStatus.SC_OK) { String msg = webAddress + " responded successfully."; writer.print(msg); LOG.info(msg); } else { String msg = webAddress + " returned HTTP error code " + status.getStatusCode() + " " + status.getReasonPhrase(); writer.print(msg); LOG.info(msg); } } catch (SSLPeerUnverifiedException x) { String msg = webAddress + " responded successfully, but could not authenticate it."; writer.print(msg); LOG.info(msg); } catch (Throwable x) { String msg = webAddress + " is registered, but could not connect to it. (" + x.getClass().getSimpleName() + ")"; writer.print(msg); LOG.info(msg); } finally { client.getConnectionManager().shutdown(); } }
From source file:fr.gcastel.freeboxV6GeekIncDownloader.services.FreeboxDownloaderService.java
private void launchDownload(String cookieCSRF, String url) throws UnsupportedEncodingException, ClientProtocolException, IOException { int splitPos = cookieCSRF.indexOf("<-->"); String cookie = cookieCSRF.substring(0, splitPos); String csrfToken = cookieCSRF.substring(splitPos + 4); // Prparation des paramtres HttpPost postReq = new HttpPost(urlFreebox + "/download.cgi"); List<NameValuePair> parametres = new ArrayList<NameValuePair>(); parametres.add(new BasicNameValuePair("url", url)); parametres.add(new BasicNameValuePair("user", "freebox")); parametres.add(new BasicNameValuePair("method", "download.http_add")); parametres.add(new BasicNameValuePair("csrf_token", csrfToken)); postReq.setEntity(new UrlEncodedFormEntity(parametres)); // Mise en place des headers postReq.setHeader("Cookie", cookie + ";"); postReq.setHeader("Referer", "http://mafreebox.freebox.fr/download.php"); // Envoi de la requte HttpParams httpParameters = new BasicHttpParams(); // Mise en place de timeouts int timeoutConnection = 5000; HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); int timeoutSocket = 5000; HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); HttpClient httpclient = new DefaultHttpClient(httpParameters); HttpParams params = httpclient.getParams(); HttpClientParams.setRedirecting(params, false); HttpResponse response = httpclient.execute(postReq); // Ok ? (302 = moved = redirection) if (response.getStatusLine().getStatusCode() != 302) { Log.d(TAG,/*from ww w. j a v a 2 s . c om*/ "Erreur lors du lancement du tlchargement - statusCode = " + response.getStatusLine().getStatusCode() + " - reason = " + response.getStatusLine().getReasonPhrase()); prepareAlertDialog("Erreur lors du lancement du tlchargement."); } }
From source file:de.hackerspacebremen.communication.HackerspaceComm.java
protected final JSONObject doInBackground(final JSONObject... data) { final String userAgent = "HackerSpaceBremen/" + this.appVersionName + "; Android/" + Build.VERSION.RELEASE + "; " + Build.MANUFACTURER + "; " + Build.DEVICE + "; " + Build.MODEL; HttpClient httpclient = new DefaultHttpClient(); HttpParams httpBodyParams = httpclient.getParams(); httpBodyParams.setParameter(CoreProtocolPNames.USER_AGENT, userAgent); String response = null;// w w w . ja v a2 s . c o m int responseCode = 0; String httpOrS = HTTPS; if (httpReq) { httpOrS = HTTP; } if (getReq) { try { final HttpURLConnection connection = client .open(new URL(httpOrS + SERVERURL + this.servletUrl + "?" + getParams)); InputStream in = null; try { // Read the response. in = connection.getInputStream(); final byte[] resp = readFully(in); response = new String(resp, Constants.UTF8); responseCode = connection.getResponseCode(); } finally { if (in != null) in.close(); } // HttpGet httpget = new HttpGet(httpOrS + SERVERURL // + this.servletUrl + "?" + getParams); // response = httpclient.execute(httpget); } catch (IOException e) { errorcode = -1; cancel(false); return null; } } else { try { HttpURLConnection connection = client.open(new URL(httpOrS + SERVERURL + this.servletUrl)); OutputStream out = null; InputStream in = null; try { // Write the request. connection.setRequestMethod("POST"); out = connection.getOutputStream(); out.write(createBody().getBytes(Constants.UTF8)); out.close(); responseCode = connection.getResponseCode(); in = connection.getInputStream(); response = readFirstLine(in); } finally { // Clean up. if (out != null) out.close(); if (in != null) in.close(); } // HttpPost httpPost = new HttpPost(httpOrS + SERVERURL // + this.servletUrl); // httpPost.setEntity(new UrlEncodedFormEntity(postParams, // "UTF-8")); // response = httpclient.execute(httpPost); } catch (IOException e) { errorcode = -1; cancel(false); return null; } } httpState = responseCode; JSONObject resData = new JSONObject(); String resString = ""; try { resString = response; resData = new JSONObject(resString); if (httpState != 200) { errorcode = resData.getInt("CODE"); cancel(false); return null; } } catch (JSONException e) { if (httpState != 200) { errorcode = httpState; } else { errorcode = -2; } cancel(false); return null; } return resData; }
From source file:net.sourceforge.subsonic.service.AudioScrobblerService.java
private String[] executeRequest(HttpUriRequest request) throws IOException { HttpClient client = new DefaultHttpClient(); HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000); HttpConnectionParams.setSoTimeout(client.getParams(), 15000); try {/*from ww w . j a va2 s. c om*/ ResponseHandler<String> responseHandler = new BasicResponseHandler(); String response = client.execute(request, responseHandler); return response.split("\\n"); } finally { client.getConnectionManager().shutdown(); } }
From source file:us.mn.state.health.lims.common.externalLinks.ExternalPatientSearch.java
private void setTimeout(HttpClient httpclient) { // this one causes a timeout if a connection is established but there is // no response within <timeout> seconds httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout); // this one causes a timeout if no connection is established within 10 seconds httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout); }
From source file:com.zrlh.llkc.funciton.Http_Utility.java
/** * Get a HttpClient object which is setting correctly . * /* w ww . jav a 2 s .c om*/ * @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, Http_Utility.SET_CONNECTION_TIMEOUT); HttpConnectionParams.setSoTimeout(httpParameters, Http_Utility.SET_SOCKET_TIMEOUT); HttpClient client = new DefaultHttpClient(httpParameters); WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); WifiInfo info = wifiManager.getConnectionInfo(); if (!wifiManager.isWifiEnabled() || -1 == info.getNetworkId()) { // ??APN? 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:com.cottsoft.weedfs.client.WeedfsClient.java
/** * Description<br>/*from w ww . j av a 2 s.c o m*/ * Cache local file to WeedFS Server * * @version v1.0.0 * @param file * @return */ public RequestResult cache(File file) { RequestResult result = null; Gson gson = new Gson(); if (!file.exists()) { throw new IllegalArgumentException("File doesn't exist"); } // HTTP REQUEST begin result = new RequestResult(); WeedAssign assignedInfo = null; BufferedReader in = null; // 1. Send assign request and get fid try { StringBuffer host = new StringBuffer(); host.append("http://"); host.append(this.masterHost); host.append(":"); host.append(this.masterPort); host.append("/"); //HttpUtil.request("http://" + this.masterHost + ":" + this.masterPort+ "/", "dir/assign", "GET") in = new BufferedReader( new InputStreamReader(HttpUtil.request(host.toString(), assign, EHttpMethod.GET))); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } // format HTTP Response to Assigned Info. assignedInfo = gson.fromJson(response.toString(), WeedAssign.class); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e.getMessage()); } finally { try { // close input stream. if (in != null) { in.close(); } } catch (IOException e) { e.printStackTrace(); } } // 2. Send cache file request on volume server FileBody fileBody = new FileBody(file, "text/plain"); HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); StringBuffer uri = new StringBuffer(); uri.append("http://"); uri.append(assignedInfo.getPublicUrl()); uri.append("/"); uri.append(assignedInfo.getFid()); HttpPost post = new HttpPost(uri.toString()); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("fileBody", fileBody); post.setEntity(entity); try { // Add File char. String response = EntityUtils.toString(client.execute(post).getEntity(), "UTF-8"); client.getConnectionManager().shutdown(); FileResult fileResult = gson.fromJson(response, FileResult.class); result.setFid(assignedInfo.getFid()); result.setSize(fileResult.getSize()); result.setStatus(true); result.setFileUrl(uri.toString()); return result; } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e.toString()); } }
From source file:nya.miku.wishmaster.http.recaptcha.RecaptchaAjax.java
static String getChallenge(String key, CancellableTask task, HttpClient httpClient, String scheme) throws Exception { if (sHandler == null) throw new Exception("handler == null (not initialized in UI thread)"); if (scheme == null) scheme = "http"; String address = scheme + "://127.0.0.1/"; String data = "<script type=\"text/javascript\"> " + "var RecaptchaOptions = { " + "theme : 'custom', " + "custom_theme_widget: 'recaptcha_widget' " + "}; " + "</script>" + "<div id=\"recaptcha_widget\" style=\"display:none\"> " + "<div id=\"recaptcha_image\"></div> " + "<input type=\"text\" id=\"recaptcha_response_field\" name=\"recaptcha_response_field\" /> " + "</div>" + "<script type=\"text/javascript\" src=\"" + scheme + "://www.google.com/recaptcha/api/challenge?k=" + key + "\"></script>"; HttpHost proxy = null;//from ww w .ja v a2s. co m if (httpClient instanceof ExtendedHttpClient) { proxy = ((ExtendedHttpClient) httpClient).getProxy(); } else if (httpClient != null) { try { proxy = ConnRouteParams.getDefaultProxy(httpClient.getParams()); } catch (Exception e) { /*ignore*/ } } if (proxy != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { return Intercepting.getInternal(address, data, task, httpClient); } else { return getChallengeInternal(address, data, task, proxy); } }