List of usage examples for org.apache.http.client.utils URLEncodedUtils format
public static String format(final Iterable<? extends NameValuePair> parameters, final Charset charset)
From source file:org.balloon_project.overflight.task.indexing.Indexing.java
private void checkEndpoint(Endpoint endpoint) { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("query", CHECK_QUERY)); String entities = URLEncodedUtils.format(nameValuePairs, "UTF-8"); // endpoint has to end with '/' String url = endpoint.getSparqlEndpoint(); if (url.endsWith("/")) { url += "?" + entities; } else {//w ww .j a va2 s . co m url += "/?" + entities; } DefaultHttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setParameter("http.socket.timeout", 10000); HttpGet getRequest = new HttpGet(url); HttpParams params = new BasicHttpParams().setParameter("http.protocol.handle-redirects", false); getRequest.setParams(params); getRequest.addHeader("accept", "application/sparql-results+xml"); getRequest.addHeader("accept-encoding", "gzip, deflate"); try { HttpResponse response = httpClient.execute(getRequest); // moved permanently if (response.getStatusLine().getStatusCode() == 301) { Header locationHeader = response.getFirstHeader("location"); if (locationHeader != null) { String redirectLocation = locationHeader.getValue().split("\\?query")[0]; logger.debug(endpoint.getEndpointID() + ": SPARQL Endpoint unreachable. Moved permanently to " + redirectLocation); endpoint.setSparqlEndpoint(redirectLocation); endpointService.updateSPARQLEndpoint(endpoint, redirectLocation); } } } catch (IOException e) { // don't react on exception, because this is only a check for HTTP moved endpoints } }
From source file:org.cruk.genologics.api.jaxb.URIAdapter.java
/** * Escape a string before conversion to a URI and, according to setting, * remove the state parameter./*from w w w . j a va2 s . co m*/ * * @param v The URI in string form. * * @return The encoded URI. */ private String escapeString(String v) { if (v != null) { int queryStart = v.indexOf('?'); if (queryStart >= 0) { List<NameValuePair> queryParts = URLEncodedUtils.parse(v.substring(queryStart + 1), UTF8); removeStateParameter(queryParts); v = v.substring(0, queryStart); if (!queryParts.isEmpty()) { v += '?' + URLEncodedUtils.format(queryParts, UTF8); } } } return v; }
From source file:net.emphased.vkclient.VkApi.java
public <T> T makeApiRequest(VkAppInfo appInfo, String method, List<NameValuePair> params, Class<T> responseClass, ContentFilter contentFilter) throws IOException, VkException { params.add(new BasicNameValuePair(METHOD_PARAM, method)); params.add(new BasicNameValuePair(API_ID_PARAM, appInfo.getApiId())); params.add(new BasicNameValuePair(FORMAT_PARAM, "JSON")); params.add(new BasicNameValuePair(VERSION_PARAM, VERSION)); String signature = makeSignature(_loginResult.getId(), appInfo.getSecret(), params); params.add(new BasicNameValuePair(SIGNATURE_PARAM, signature)); String url = DEFAULT_URL_PREFIX + URLEncodedUtils.format(params, "UTF-8"); HttpGet get = new HttpGet(url); HttpResponse resp = _client.getHttpClient().execute(get, _httpContext); String respContent = EntityUtils.toString(resp.getEntity()); if (contentFilter != null) { respContent = contentFilter.filter(respContent); }//from ww w .j av a2s .co m T result = VkClient.getObjectMapper().readValue(respContent, responseClass); return result; }
From source file:org.mahasen.client.Upload.java
/** * @param uploadFile//www . ja va 2s . c o m * @param tags * @param folderStructure * @param addedProperties * @throws IOException */ public void upload(File uploadFile, String tags, String folderStructure, List<NameValuePair> addedProperties) throws IOException, MahasenClientException, URISyntaxException { httpclient = new DefaultHttpClient(); if (addedProperties != null) { this.customProperties = addedProperties; } try { System.out.println(" Is Logged : " + clientLoginData.isLoggedIn()); if (clientLoginData.isLoggedIn() == true) { httpclient = WebClientSSLWrapper.wrapClient(httpclient); File file = uploadFile; if (file.exists()) { if (!folderStructure.equals("")) { customProperties.add(new BasicNameValuePair("folderStructure", folderStructure)); } customProperties.add(new BasicNameValuePair("fileName", file.getName())); customProperties.add(new BasicNameValuePair("tags", tags)); URI uri = URIUtils.createURI("https", clientLoginData.getHostNameAndPort(), -1, "/mahasen/upload_ajaxprocessor.jsp", URLEncodedUtils.format(customProperties, "UTF-8"), null); HttpPost httppost = new HttpPost(uri); InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1); reqEntity.setContentType("binary/octet-stream"); reqEntity.setChunked(true); httppost.setEntity(reqEntity); httppost.setHeader("testHeader", "testHeadervalue"); System.out.println("executing request " + httppost.getRequestLine()); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); EntityUtils.consume(resEntity); if (response.getStatusLine().getStatusCode() == 900) { throw new MahasenClientException(String.valueOf(response.getStatusLine())); } } } else { System.out.println("User has to be logged in to perform this function"); } } finally { httpclient.getConnectionManager().shutdown(); } }
From source file:com.autonomy.nonaci.indexing.impl.IndexCommandImpl.java
@Override public String getQueryString() { final List<NameValuePair> pairs = new ArrayList<NameValuePair>(parameters.size()); for (final Map.Entry<String, String> entry : parameters.entrySet()) { pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); }//from w w w . j a v a 2s.co m return URLEncodedUtils.format(pairs, "UTF-8"); }
From source file:com.hollowsoft.library.utility.request.HttpRequest.java
/** * * @param url/*from ww w .ja v a2 s . c o m*/ * @param nameValuePairList * @param headerArray * @return * @throws RequestException */ public JsonNode doGet(final String url, final List<NameValuePair> nameValuePairList, final Header... headerArray) throws RequestException { if (url == null || url.isEmpty()) { throw new IllegalArgumentException("The url cannot be null or empty."); } final String parameterString = URLEncodedUtils.format(nameValuePairList, Constants.DEFAULT_CHARSET.name()); try { final HttpGet httpGet = new HttpGet(url + "?" + parameterString); httpGet.setHeaders(headerArray); final HttpEntity httpEntity = httpClient.execute(httpGet).getEntity(); return new ObjectMapper().reader().readTree(httpEntity.getContent()); } catch (final ClientProtocolException e) { throw new RequestException(e); } catch (final JsonProcessingException e) { throw new RequestException(e); } catch (final IllegalStateException e) { throw new RequestException(e); } catch (final IOException e) { throw new RequestException(e); } }
From source file:com.hp.hpl.jena.sparql.engine.http.Params.java
/** Query string, without leading "?" */ public String httpString() { return URLEncodedUtils.format(paramList, StandardCharsets.UTF_8); }
From source file:org.mahasen.util.DeleteUtil.java
/** * @param fileToDelete// www .ja v a2 s . co m * @throws MalformedURLException * @throws RegistryException */ public void delete(String fileToDelete) throws MalformedURLException, RegistryException, MahasenConfigurationException, MahasenException { Id resourceId = Id.build(String.valueOf(fileToDelete.hashCode())); String currentFileName = null; try { MahasenResource mahasenResource = mahasenManager.lookupDHT(resourceId); if (mahasenManager.lookupDHT(resourceId) == null) { throw new MahasenException("File not found"); } String fileName = mahasenResource.getProperty(MahasenConstants.FILE_NAME).toString(); Hashtable<String, Vector<String>> iptable = mahasenResource.getSplittedPartsIpTable(); int totalNoOfParts = 0; for (String partName : mahasenResource.getPartNames()) { totalNoOfParts += iptable.get(partName).size(); } setStoredNoOfParts(totalNoOfParts); for (String partName : mahasenResource.getPartNames()) { currentFileName = fileName + "." + partName; for (int i = 0; i < iptable.get(partName).size(); i++) { String nodeIp = iptable.get(partName).get(i); ArrayList<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair(MahasenConstants.FILE_NAME, fileName + "." + partName)); URI uri = null; try { uri = URIUtils.createURI("https", nodeIp + ":" + MahasenConstants.SERVER_PORT, -1, "/mahasen/delete_request_ajaxprocessor.jsp", URLEncodedUtils.format(qparams, "UTF-8"), null); MahasenDeleteWorker mahasenDeleteWorker = new MahasenDeleteWorker(uri); Thread deleteThread = new Thread(mahasenDeleteWorker); deleteThread.start(); } catch (URISyntaxException e) { log.info("URI not found"); return; } } } final BlockFlag blockFlag = new BlockFlag(true, 1500); while (true) { if (storedNoOfParts.intValue() == 0) { MahasenResource resourceToDelete = mahasenManager.lookupDHT(resourceId); mahasenManager.deletePropertyFromTreeMap(resourceId, resourceToDelete); mahasenManager.deleteContent(resourceId); blockFlag.unblock(); break; } if (blockFlag.isBlocked()) { mahasenManager.getNode().getEnvironment().getTimeSource().sleep(10); } else { throw new MahasenException("Time out in delete operation for " + fileName); } } } catch (InterruptedException e) { log.error("Error deleting file : " + currentFileName); } }
From source file:org.mahasen.client.Delete.java
/** * @param fileName/*from w w w . ja v a2 s. c o m*/ * @param hostIP * @throws IOException */ public void delete(String fileName, String hostIP) throws IOException, AuthenticationExceptionException, URISyntaxException, MahasenClientException { httpclient = new DefaultHttpClient(); clientLogin = new ClientLogin(); ClientConfiguration clientConfiguration = ClientConfiguration.getInstance(); try { System.setProperty("javax.net.ssl.trustStore", clientConfiguration.getTrustStorePath()); System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon"); System.setProperty("javax.net.ssl.trustStoreType", "JKS"); String userName = clientConfiguration.getUserName(); String passWord = clientConfiguration.getPassWord(); String hostAndPort = hostIP + ":" + clientConfiguration.getPort(); ClientLoginData loginData = clientLogin.remoteLogin(hostAndPort, userName, passWord); String logincookie = loginData.getCookie(); Boolean isLogged = loginData.isLoggedIn(); System.out.println("Login Cookie : " + logincookie + " Is Logged : " + isLogged); if (isLogged == true) { httpclient = WebClientSSLWrapper.wrapClient(httpclient); List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("fileName", fileName)); URI uri = URIUtils.createURI("https", hostAndPort, -1, "/mahasen/delete_ajaxprocessor.jsp", URLEncodedUtils.format(qparams, "UTF-8"), null); HttpPost httppost = new HttpPost(uri); System.out.println("executing request " + httppost.getRequestLine()); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); EntityUtils.consume(resEntity); if (response.getStatusLine().getStatusCode() == 900) { throw new MahasenClientException(String.valueOf(response.getStatusLine())); } } else { System.out.println("User has to be logged in to perform this function"); } } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } }
From source file:net.neoturbine.autolycus.internal.BusTimeAPI.java
/** * Requests the XML data for a given action and parameters. Matches the * <code>system</code> input with a hard-coded internal list to know which * server to use. Note that this MUST not be run in the UI thread. * // w w w. j ava 2 s . c o m * @param context * Currently unused, but needed for analytics. * @param verb * The string in the last part of the Base URL within the API * documentation. * @param system * One of the internally supported transit systems. * @param params * a Bundle containing the parameters to be passed within its * extras. * @return an XmlPullParser with the XML tree resulting from this API call. * * @throws ClientProtocolException * @throws IOException * @throws XmlPullParserException */ private static XmlPullParser loadData(Context context, String verb, String system, Bundle params) throws ClientProtocolException, IOException, XmlPullParserException { ArrayList<NameValuePair> qparams = new ArrayList<NameValuePair>(); if (params != null) { for (String name : params.keySet()) { qparams.add(new BasicNameValuePair(name, params.getString(name))); } } String server = ""; String key = ""; if (system.equals("Chicago Transit Authority")) { server = "www.ctabustracker.com"; key = "HeDbySM4CUDgRDsrGnRGZmD6K"; } else if (system.equals("Ohio State University TRIP")) { server = "trip.osu.edu"; key = "auixft7SWR3pWAcgkQfnfJpXt"; } else if (system.equals("MTA New York City Transit")) { server = "bustime34.mta.info"; key = "t7YxRNCmvVCfrZzrcMFeYegjp"; } qparams.add(new BasicNameValuePair("key", key)); // assemble the url URI uri; try { uri = URIUtils.createURI("http", // Protocol server, // server 80, // specified in API documentation "/bustime/api/v1/" + verb, // path URLEncodedUtils.format(qparams, "UTF-8"), null); } catch (URISyntaxException e) { // shouldn't happen throw new RuntimeException(e); } // assemble our request HttpClient httpClient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(uri); Log.i(TAG, "Retrieving " + httpget.getURI().toString()); // from localytics recordEvent(context,system,verb,false); // ah, the blocking HttpResponse response = httpClient.execute(httpget); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new RuntimeException(response.getStatusLine().toString()); } InputStream content = response.getEntity().getContent(); XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser xpp = factory.newPullParser(); xpp.setInput(content, null); return xpp; }