List of usage examples for org.apache.http.client HttpClient getParams
@Deprecated HttpParams getParams();
From source file:com.streamreduce.AbstractInContainerTestCase.java
/** * Makes a request to the given url using the given method and possibly submitting * the given data. If you need the request to be an authenticated request, pass in * your authentication token as well.// w ww. j a v a 2 s. co m * * @param url the url for the request * @param method the method to use for the request * @param data the data, if any, for the request * @param authnToken the token retrieved during authentication * @param type API or GATEWAY, tells us the auth token key to use * @return the response as string (This is either the response payload or the status code if no payload is sent) * @throws Exception if something goes wrong */ public String makeRequest(String url, String method, Object data, String authnToken, AuthTokenType type) throws Exception { HttpClient httpClient = new DefaultHttpClient(); HttpRequestBase request; String actualPayload; // Set the User-Agent to be safe httpClient.getParams().setParameter(HttpProtocolParams.USER_AGENT, Constants.NODEABLE_HTTP_USER_AGENT); // Create the request object if (method.equals("DELETE")) { request = new HttpDelete(url); } else if (method.equals("GET")) { request = new HttpGet(url); } else if (method.equals("POST")) { request = new HttpPost(url); } else if (method.equals("PUT")) { request = new HttpPut(url); } else if (method.equals("HEAD")) { request = new HttpHead(url); } else { throw new IllegalArgumentException("The method you specified is not supported."); } // Put data into the request for POST and PUT requests if (method.equals("POST") || method.equals("PUT")) { HttpEntityEnclosingRequestBase eeMethod = (HttpEntityEnclosingRequestBase) request; String requestBody = data instanceof JSONObject ? ((JSONObject) data).toString() : new ObjectMapper().writeValueAsString(data); eeMethod.setEntity(new StringEntity(requestBody, MediaType.APPLICATION_JSON, "UTF-8")); } // Add the authentication token to the request if (authnToken != null) { if (type.equals(AuthTokenType.API)) { request.addHeader(Constants.NODEABLE_AUTH_TOKEN, authnToken); } else if (type.equals(AuthTokenType.GATEWAY)) { request.addHeader(Constants.NODEABLE_API_KEY, authnToken); } else { throw new Exception("Unsupported Type of " + type + " for authToken " + authnToken); } } // Execute the request try { HttpResponse response = httpClient.execute(request); String payload = IOUtils.toString(response.getEntity().getContent()); // To work around HEAD, where we cannot receive a payload, and other scenarios where the payload could // be empty, let's stuff the response status code into the response. actualPayload = payload != null && payload.length() > 0 ? payload : Integer.toString(response.getStatusLine().getStatusCode()); } finally { request.releaseConnection(); } return actualPayload; }
From source file:com.gitblit.plugin.hipchat.HipChatter.java
/** * Send a payload message.//from ww w. java2 s .c om * * @param payload * @throws IOException */ public void send(Payload payload) throws IOException { RepoConfig config = payload.getConfig(); if (payload.getConfig() == null) { setRoom(null, payload); } String hipchatUrl = String.format("https://api.hipchat.com/v2/room/%s/notification?auth_token=%s", config.getRoomName(), config.getToken()); Gson gson = new GsonBuilder().create(); HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(hipchatUrl); post.getParams().setParameter(CoreProtocolPNames.USER_AGENT, Constants.NAME + "/" + Constants.getVersion()); post.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8"); client.getParams().setParameter(AllClientPNames.CONNECTION_TIMEOUT, 5000); client.getParams().setParameter(AllClientPNames.SO_TIMEOUT, 5000); String body = gson.toJson(payload); StringEntity entity = new StringEntity(body, "UTF-8"); entity.setContentType("application/json"); post.setEntity(entity); HttpResponse response = client.execute(post); int rc = response.getStatusLine().getStatusCode(); if (HttpStatus.SC_NO_CONTENT == rc) { // This is the expected result code // https://www.hipchat.com/docs/apiv2/method/send_room_notification // 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("HipChat plugin sent:"); log.error(body); log.error("HipChat returned:"); log.error(result); throw new IOException(String.format("HipChat Error (%s): %s", rc, result)); } }
From source file:org.wso2.dss.integration.test.sparql.SPARQLServiceTestCase.java
private boolean isExternalEndpointAvailable() throws IOException { HttpClient httpClient = new DefaultHttpClient(); String url = "http://semantic.eea.europa.eu/sparql?query="; String query = "PREFIX rdfs:<http://www.w3.org/2000/01/rdf-schema#>\n" + "PREFIX cr:<http://cr.eionet.europa.eu/ontologies/contreg.rdf#>\n" + "SELECT * WHERE { ?bookmark a cr:SparqlBookmark;rdfs:label ?label} LIMIT 50"; url = url + URLEncoder.encode(query, "UTF-8"); HttpGet httpGet = new HttpGet(url); httpClient.getParams().setParameter("http.socket.timeout", 300000); httpGet.setHeader("Accept", "text/xml"); HttpResponse httpResponse = httpClient.execute(httpGet); if (httpResponse.getStatusLine().getStatusCode() == 200) { return true; }//from w ww .j a v a 2s .c om return false; }
From source file:com.zzl.zl_app.cache.Utility.java
/** * Get a HttpClient object which is setting correctly . * //from www. ja v a2 s. 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); 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.cydroid.coreframe.web.img.fetcher.ImageFetcher.java
private Bitmap processBitmap(String url) { // Bitmap bitmap=null; // try { // bitmap= getImage(url); // } catch (Exception e) { // e.printStackTrace(); // }/*from ww w. ja v a2 s . co m*/ // return bitmap; LogUtil.i("processBitmap====" + url); Bitmap bitmap = null; // AndroidHttpClient is not allowed to be used from the main thread final HttpClient client = AndroidHttpClient.newInstance("Android"); // final HttpClient client = HttpsClient.getInstance() // .getHttpsClient(); final HttpGet getRequest = new HttpGet(url); client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000); client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000); try { HttpResponse response = client.execute(getRequest); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url); return null; } final HttpEntity entity = response.getEntity(); if (entity != null) { InputStream inputStream = entity.getContent(); FlushedInputStream mFlushedInputStream = new FlushedInputStream(inputStream); try { BitmapFactory.Options options = new BitmapFactory.Options(); // options.inJustDecodeBounds = true; // BitmapFactory.decodeStream(mFlushedInputStream,null,options); //// int imageHeight = options.outHeight; //// int imageWidth = options.outWidth; // // int calculate=calculateInSampleSize(options,720,1080); //// options = new BitmapFactory.Options(); //// inputStream.reset(); options.inSampleSize = inSampleSize; options.inJustDecodeBounds = false; LogUtil.i("inSampleSize====" + inSampleSize); bitmap = BitmapFactory.decodeStream(mFlushedInputStream, null, options); } catch (OutOfMemoryError e) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 4; bitmap = BitmapFactory.decodeStream(mFlushedInputStream, null, options); } finally { if (inputStream != null) { inputStream.close(); inputStream = null; } entity.consumeContent(); } } return bitmap; } catch (IOException e) { getRequest.abort(); Log.w("LOG_TAG", "I/O error while retrieving bitmap from " + url, e); } catch (IllegalStateException e) { getRequest.abort(); Log.w("LOG_TAG", "Incorrect URL: " + url); } catch (Exception e) { getRequest.abort(); Log.w("LOG_TAG", "Error while retrieving bitmap from " + url, e); } finally { if ((client instanceof AndroidHttpClient)) { ((AndroidHttpClient) client).close(); } } return null; }
From source file:com.gitblit.plugin.slack.Slacker.java
/** * Send a payload message.//w w w . j a va2s. com * * @param payload * @throws IOException */ public void send(Payload payload) throws IOException { String slackUrl = getURL(); payload.setUnfurlLinks(true); if (StringUtils.isEmpty(payload.getUsername())) { payload.setUsername(Constants.NAME); } String defaultChannel = runtimeManager.getSettings().getString(Plugin.SETTING_DEFAULT_CHANNEL, null); if (!StringUtils.isEmpty(defaultChannel) && StringUtils.isEmpty(payload.getChannel())) { // specify the default channel if (defaultChannel.charAt(0) != '#' && defaultChannel.charAt(0) != '@') { defaultChannel = "#" + defaultChannel; } // channels must be lowercase payload.setChannel(defaultChannel.toLowerCase()); } String defaultEmoji = runtimeManager.getSettings().getString(Plugin.SETTING_DEFAULT_EMOJI, null); if (!StringUtils.isEmpty(defaultEmoji)) { if (StringUtils.isEmpty(payload.getIconEmoji()) && StringUtils.isEmpty(payload.getIconUrl())) { // specify the default emoji payload.setIconEmoji(defaultEmoji); } } Gson gson = new GsonBuilder().create(); String json = gson.toJson(payload); log.debug(json); HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(slackUrl); post.getParams().setParameter(CoreProtocolPNames.USER_AGENT, Constants.NAME + "/" + Constants.getVersion()); post.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8"); client.getParams().setParameter(AllClientPNames.CONNECTION_TIMEOUT, 5000); client.getParams().setParameter(AllClientPNames.SO_TIMEOUT, 5000); List<NameValuePair> nvps = new ArrayList<NameValuePair>(1); nvps.add(new BasicNameValuePair("payload", json)); post.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8")); HttpResponse response = client.execute(post); int rc = response.getStatusLine().getStatusCode(); if (HttpStatus.SC_OK == rc) { // 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("Slack plugin sent:"); log.error(json); log.error("Slack returned:"); log.error(result); throw new IOException(String.format("Slack Error (%s): %s", rc, result)); } }
From source file:de.azapps.mirakel.sync.Network.java
private String downloadUrl(String myurl) throws IOException, URISyntaxException { if (token != null) { myurl += "?authentication_key=" + token; }//from ww w. j a va 2s . c o m if (myurl.indexOf("https") == -1) { Integer[] t = { NoHTTPS }; publishProgress(t); } /* * String authorizationString = null; * if (syncTyp == ACCOUNT_TYPES.CALDAV) { * authorizationString = "Basic " * + Base64.encodeToString( * (username + ":" + password).getBytes(), * Base64.NO_WRAP); * } */ CredentialsProvider credentials = new BasicCredentialsProvider(); credentials.setCredentials(new AuthScope(new URI(myurl).getHost(), -1), new UsernamePasswordCredentials(username, password)); HttpParams params = new BasicHttpParams(); params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpConnectionParams.setTcpNoDelay(params, true); HttpClient httpClient; /* * if(syncTyp == ACCOUNT_TYPES.MIRAKEL) * httpClient = sslClient(client); * else { */ DefaultHttpClient tmpHttpClient = new DefaultHttpClient(params); tmpHttpClient.setCredentialsProvider(credentials); httpClient = tmpHttpClient; // } httpClient.getParams().setParameter("http.protocol.content-charset", HTTP.UTF_8); HttpResponse response; try { switch (mode) { case GET: Log.v(TAG, "GET " + myurl); HttpGet get = new HttpGet(); get.setURI(new URI(myurl)); response = httpClient.execute(get); break; case PUT: Log.v(TAG, "PUT " + myurl); HttpPut put = new HttpPut(); if (syncTyp == ACCOUNT_TYPES.CALDAV) { put.addHeader(HTTP.CONTENT_TYPE, "text/calendar; charset=utf-8"); } put.setURI(new URI(myurl)); put.setEntity(new StringEntity(content, HTTP.UTF_8)); Log.v(TAG, content); response = httpClient.execute(put); break; case POST: Log.v(TAG, "POST " + myurl); HttpPost post = new HttpPost(); post.setURI(new URI(myurl)); post.setEntity(new UrlEncodedFormEntity(headerData, HTTP.UTF_8)); response = httpClient.execute(post); break; case DELETE: Log.v(TAG, "DELETE " + myurl); HttpDelete delete = new HttpDelete(); delete.setURI(new URI(myurl)); response = httpClient.execute(delete); break; case REPORT: Log.v(TAG, "REPORT " + myurl); HttpReport report = new HttpReport(); report.setURI(new URI(myurl)); Log.d(TAG, content); report.setEntity(new StringEntity(content, HTTP.UTF_8)); response = httpClient.execute(report); break; default: Log.wtf("HTTP-MODE", "Unknown Http-Mode"); return null; } } catch (Exception e) { Log.e(TAG, "No Networkconnection available"); Log.w(TAG, Log.getStackTraceString(e)); return ""; } Log.v(TAG, "Http-Status: " + response.getStatusLine().getStatusCode()); if (response.getEntity() == null) return ""; String r = EntityUtils.toString(response.getEntity(), HTTP.UTF_8); Log.d(TAG, r); return r; }
From source file:org.eclipse.dirigible.ide.common.io.ProxyUtils.java
public static HttpClient getHttpClient(boolean trustAll) { HttpClient httpClient = null; // Local case only // try {/* www. j a v a 2s .co m*/ // loadLocalBuildProxy(); // } catch (IOException e) { // logger.error(e.getMessage(), e); // } if (trustAll) { try { SchemeSocketFactory plainSocketFactory = PlainSocketFactory.getSocketFactory(); SchemeSocketFactory sslSocketFactory = new SSLSocketFactory(createTrustAllSSLContext()); Scheme httpScheme = new Scheme("http", 80, plainSocketFactory); Scheme httpsScheme = new Scheme("https", 443, sslSocketFactory); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(httpScheme); schemeRegistry.register(httpsScheme); ClientConnectionManager cm = new SingleClientConnManager(schemeRegistry); httpClient = new DefaultHttpClient(cm); } catch (Exception e) { httpClient = new DefaultHttpClient(); } } else { httpClient = new DefaultHttpClient(); } String httpProxyHost = EnvUtils.getEnv(HTTP_PROXY_HOST); String httpProxyPort = EnvUtils.getEnv(HTTP_PROXY_PORT); if ((httpProxyHost != null) && (httpProxyPort != null)) { HttpHost httpProxy = new HttpHost(httpProxyHost, Integer.parseInt(httpProxyPort)); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, httpProxy); } return httpClient; }