List of usage examples for org.apache.http.client.utils URIUtils createURI
@Deprecated public static URI createURI(final String scheme, final String host, final int port, final String path, final String query, final String fragment) throws URISyntaxException
From source file:org.getwheat.harvest.library.RequestProcessor.java
private HttpUriRequest buildRequest(final Request<?> request, final UserCredentials credentials) throws URISyntaxException, UnsupportedEncodingException { final HttpUriRequest uriRequest = request.getHttpMethod().getRequest( URIUtils.createURI(VALUE_SCHEME, manager.getHostname(), -1, request.getResourcePath(), URLEncodedUtils.format(request.getParameters(), VALUE_UTF8), null).toString(), request.getRequestContent()); request.getTransformer().addContentTypeHeaders(uriRequest); addBasicAuthHeaders(uriRequest, credentials); return uriRequest; }
From source file:de.huxhorn.whistler.services.JmpUrlShortener.java
public String shorten(String url) { List<NameValuePair> qparams = new ArrayList<NameValuePair>(); // http://api.bit.ly/shorten?version=2.0.1&longUrl=http://cnn.com&login=bitlyapidemo&apiKey=R_0da49e0a9118ff35f52f629d2d71bf07 qparams.add(new BasicNameValuePair("version", "2.0.1")); qparams.add(new BasicNameValuePair("longUrl", url)); if (login != null) { qparams.add(new BasicNameValuePair("login", login)); qparams.add(new BasicNameValuePair("apiKey", apiKey)); qparams.add(new BasicNameValuePair("history", "1")); }//from w w w .j a v a 2s. co m try { BasicHttpParams params = new BasicHttpParams(); /*params.setParameter(CookieSpecPNames.DATE_PATTERNS, Arrays.asList("EEE, dd-MMM-yyyy HH:mm:ss z", "EEE, dd MMM yyyy HH:mm:ss z")); params.setParameter( ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH); BestMatchSpecFactory factory = new BestMatchSpecFactory(); CookieSpec cookiespec = factory.newInstance(params); */ DefaultHttpClient httpclient = new DefaultHttpClient(params); //httpclient.setCookieSpecs(cookiespec); //BestMatchSpecFactory factory = new BestMatchSpecFactory(); //CookieSpec cookiespec = factory.newInstance(params); //BasicHeader header = new BasicHeader("Set-Cookie", // "asid=011e7014f5e7718e02d893335aa5a16e; path=/; " + // "expires=Wed, 16-May-2018 17:13:32 GMT"); //CookieOrigin origin = new CookieOrigin("localhost", 80, "/", false); //List<Cookie> cookies = cookiespec.parse(header, origin); //System.out.println(cookies); // TODO: Cookie spec URI uri = URIUtils.createURI("http", "api.j.mp", -1, "/shorten", URLEncodedUtils.format(qparams, "UTF-8"), null); HttpGet httpget = new HttpGet(uri); if (logger.isDebugEnabled()) logger.debug("HttpGet.uri={}", httpget.getURI()); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); JsonFactory f = new JsonFactory(); JsonParser jp = f.createJsonParser(instream); JmpShortenResponse responseObj = new JmpShortenResponse(); for (;;) { JsonToken token = jp.nextToken(); String fieldname = jp.getCurrentName(); if (logger.isDebugEnabled()) logger.debug("Token={}, currentName={}", token, fieldname); if (token == JsonToken.START_OBJECT) { continue; } if (token == JsonToken.END_OBJECT) { break; } if ("errorCode".equals(fieldname)) { token = jp.nextToken(); responseObj.setErrorCode(jp.getIntValue()); } else if ("errorMessage".equals(fieldname)) { token = jp.nextToken(); responseObj.setErrorMessage(jp.getText()); } else if ("statusCode".equals(fieldname)) { token = jp.nextToken(); responseObj.setStatusCode(jp.getText()); } else if ("results".equals(fieldname)) { // contains an object Map<String, ShortenedUrl> results = parseResults(jp); responseObj.setResults(results); } else { throw new IllegalStateException("Unrecognized field '" + fieldname + "'!"); } } Map<String, ShortenedUrl> results = responseObj.getResults(); if (results == null) { return null; } ShortenedUrl shortened = results.get(url); if (shortened == null) { return null; } if (logger.isDebugEnabled()) logger.debug("JmpShortenResponse: {}", responseObj); if ("OK".equals(responseObj.getStatusCode())) { return shortened.getShortUrl(); } // TODO: better error handling if (logger.isWarnEnabled()) logger.warn("JmpShortenResponse: {}", responseObj); } } catch (IOException ex) { if (logger.isWarnEnabled()) logger.warn("Exception!", ex); } catch (URISyntaxException ex) { if (logger.isWarnEnabled()) logger.warn("Exception!", ex); } // catch (MalformedCookieException ex) // { // if (logger.isWarnEnabled()) logger.warn("Exception!", ex); // } return null; }
From source file:com.cloudapp.rest.CloudApi.java
/** * Create a bookmark./* www. java2 s.co m*/ * * @param name * The name of the bookmark. * @param url * The URL of the bookmark * @return a JSONObject with the info that was return by the CloudApp servers. * @throws CloudApiException */ public JSONObject createBookmark(String name, String url) throws CloudApiException { HttpPost request = null; try { // Apparently we have to post a JSONObject .. JSONObject item = new JSONObject(); item.put("name", name); item.put("redirect_url", url); JSONObject bodyObj = new JSONObject(); bodyObj.put("item", item); String body = bodyObj.toString(2); System.out.println(bodyObj.toString(2)); // Prepare the parameters List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("item[redirect_url]", url)); nvps.add(new BasicNameValuePair("item[name]", name)); // Prepare the request. URI uri = URIUtils.createURI("http", "my.cl.ly", -1, "/items", URLEncodedUtils.format(nvps, "UTF-8"), null); request = new HttpPost(uri); request.setHeader("Accept", "application/json"); // Fire it HttpResponse response = client.execute(request); int status = response.getStatusLine().getStatusCode(); body = EntityUtils.toString(response.getEntity()); // Only 200 means success. if (status == 200) { return new JSONObject(body); } throw new CloudApiException(status, body, null); } catch (JSONException e) { LOGGER.error("Error when trying to convert the return output to JSON.", e); throw new CloudApiException(500, e.getMessage(), e); } catch (IOException e) { LOGGER.error("Unable to create bookmark.", e); throw new CloudApiException(500, e.getMessage(), e); } catch (URISyntaxException e) { LOGGER.error("Unable to create bookmark.", e); throw new CloudApiException(500, e.getMessage(), e); } finally { if (request != null) { request.abort(); } } }
From source file:org.geosdi.geoplatform.connector.CatalogContextTest.java
@Before public void setUp() throws Exception { try {/*from ww w.j ava 2 s. c o m*/ HttpClient client = new DefaultHttpClient(); List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("SERVICE", "CSW")); qparams.add(new BasicNameValuePair("REQUEST", "GetCapabilities")); URI uri = URIUtils.createURI("http", CSW_HOST, -1, CSW_PATH, URLEncodedUtils.format(qparams, "UTF-8"), null); HttpGet get = new HttpGet(uri); HttpResponse response = client.execute(get); this.entity = response.getEntity(); } catch (URISyntaxException ex) { logger.error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ " + ex.getMessage()); } catch (ClientProtocolException ex) { logger.error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ " + ex.getMessage()); } catch (IOException ex) { logger.error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ " + ex.getMessage()); } }
From source file:org.soyatec.windowsazure.authenticate.SharedKeyCredentialsWrapper.java
/** * Replace the uri container name.//w w w . j av a 2s . c o m * * @param uri * @param accountName * @return The uri after be replaced the account name with the input * accountName. */ private URI replaceAccountName(URI uri, String accountName) { try { String host = uri.getHost(); String[] temp = host.split("\\."); temp[0] = accountName; return URIUtils.createURI(uri.getScheme(), join(".", temp), uri.getPort(), HttpUtilities.getNormalizePath(uri), (uri.getQuery() == null ? Utilities.emptyString() : uri.getQuery()), uri.getFragment()); } catch (URISyntaxException e) { Logger.error("", e); } return uri; }
From source file:org.coffeebreaks.validators.w3c.W3cMarkupValidator.java
private ValidationResult validateW3cMarkup(String type, String value, boolean get) throws IOException { HttpClient httpclient = new DefaultHttpClient(); HttpRequestBase method;//from ww w .j a v a 2s . co m if (get) { List<NameValuePair> qParams = new ArrayList<NameValuePair>(); qParams.add(new BasicNameValuePair("output", "soap12")); qParams.add(new BasicNameValuePair(type, value)); try { URI uri = new URI(baseUrl + (baseUrl.endsWith("/") ? "" : "/") + "check"); URI uri2 = URIUtils.createURI(uri.getScheme(), uri.getHost(), uri.getPort(), uri.getPath(), URLEncodedUtils.format(qParams, "UTF-8"), null); method = new HttpGet(uri2); } catch (URISyntaxException e) { throw new IllegalArgumentException("invalid uri. Check your baseUrl " + baseUrl, e); } } else { HttpPost httpPost = new HttpPost(baseUrl + (baseUrl.endsWith("/") ? "" : "/") + "check"); List<NameValuePair> formParams = new ArrayList<NameValuePair>(); formParams.add(new BasicNameValuePair("output", "soap12")); formParams.add(new BasicNameValuePair(type, value)); UrlEncodedFormEntity requestEntity = new UrlEncodedFormEntity(formParams, "UTF-8"); httpPost.setEntity(requestEntity); method = httpPost; } HttpResponse response = httpclient.execute(method); HttpEntity responseEntity = response.getEntity(); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode >= HttpStatus.SC_BAD_REQUEST) { throw new IllegalStateException( "Unexpected HTTP status code: " + statusCode + ". Implementation error ?"); } if (responseEntity == null) { throw new IllegalStateException( "No entity but HTTP status code: " + statusCode + ". Server side error ?"); } InputStream entityContentInputStream = responseEntity.getContent(); StringWriter output = new StringWriter(); IOUtils.copy(entityContentInputStream, output, "UTF-8"); final String soap = output.toString(); // we can use the response headers instead of the soap // final W3cSoapValidatorSoapOutput soapObject = parseSoapObject(soap); String headerValue = getHeaderValue(response, "X-W3C-Validator-Status"); final boolean indeterminate = headerValue.equals("Abort"); final int errorCount = Integer.parseInt(getHeaderValue(response, "X-W3C-Validator-Errors")); final int warningCount = Integer.parseInt(getHeaderValue(response, "X-W3C-Validator-Warnings")); return new ValidationResult() { public boolean isResultIndeterminate() { return indeterminate; } public int getErrorCount() { return errorCount; } public int getWarningCount() { return warningCount; } public String getResponseContent() { return soap; } }; }
From source file:com.jzboy.couchdb.http.URITemplates.java
/** * URI used to see a listing of changes made to documents in a database * @see <a href="http://wiki.apache.org/couchdb/HTTP_database_API#Changes">CouchDB Wiki</a> *///from w w w . jav a2s .c o m public static URI dbChanges(String host, int port, String dbName, String params) throws URISyntaxException { return URIUtils.createURI("http", host, port, dbName + "/_changes", params, null); }
From source file:org.openiot.gsn.http.ac.GSNClient.java
public boolean doLogin(String username, String password) throws IOException, KeyStoreException { ArrayList formparams = new ArrayList(); formparams.add(new BasicNameValuePair("username", username)); formparams.add(new BasicNameValuePair("password", password)); UrlEncodedFormEntity entityform = new UrlEncodedFormEntity(formparams, "UTF-8"); boolean loginOK = false; try {//w w w . j a v a 2 s . com URI uri = URIUtils.createURI("https", this.host, this.gsnhttpsport, "/gsn/MyLoginHandlerServlet", null, null); HttpPost httppost = new HttpPost(uri); httppost.addHeader("client", "apache"); logger.info("executing request" + httppost.getRequestLine()); httppost.setEntity(entityform); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); Header header = response.getFirstHeader("logedin"); if (header != null) { if (header.getValue().equals("yes")) { loginOK = true; } else if (header.getValue().equals("no")) { loginOK = false; } } logger.info("---------------------------------------- " + response.getStatusLine()); if (entity != null) { logger.info("Response content length: " + entity.getContentLength()); logger.info(EntityUtils.toString(entity)); } if (entity != null) { entity.consumeContent(); } } catch (Exception e) { logger.error("ERROR IN DOLOGIN: Exception while creating uri"); logger.error(e.getMessage(), e); } return loginOK; }