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.geosdi.geoplatform.connector.CatalogContextTest.java
@Before public void setUp() throws Exception { try {/*from w w w . j av a2 s .co 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:com.github.lpezet.antiope.util.HttpUtils.java
public static String encodeParameters(Map<String, String> pParameters) { List<NameValuePair> nameValuePairs = null; if (pParameters.size() > 0) { nameValuePairs = new ArrayList<NameValuePair>(pParameters.size()); for (Entry<String, String> entry : pParameters.entrySet()) { nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); }/*w ww .jav a2s . c om*/ } String encodedParams = null; if (nameValuePairs != null) { encodedParams = URLEncodedUtils.format(nameValuePairs, DEFAULT_ENCODING); } return encodedParams; }
From source file:rtdc.android.impl.AndroidHttpRequest.java
/** * {@inheritDoc}/*from w w w. j av a 2 s. c om*/ */ @Override public void execute(final AsyncCallback<HttpResponse> callback) { Response.Listener listener = new Response.Listener<String>() { @Override public void onResponse(String response) { logger.log(Level.WARNING, response); callback.onSuccess(new AndroidHttpResponse(200, response)); } }; Response.ErrorListener errorListener = new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { callback.onError(": server request timed out!"); error.printStackTrace(); } }; //Format the parameters List<BasicNameValuePair> paramsAsValuePairs = new LinkedList<BasicNameValuePair>(); for (Map.Entry<String, String> param : params.entrySet()) paramsAsValuePairs.add(new BasicNameValuePair(param.getKey(), param.getValue())); if (requestMethod == 0) url += "?" + URLEncodedUtils.format(paramsAsValuePairs, "UTF-8"); else requestBody = URLEncodedUtils.format(paramsAsValuePairs, "UTF-8"); JsonObjectRequest request = new JsonObjectRequest(requestMethod, url, listener, errorListener); StringBuilder sb = new StringBuilder("Sending at " + url + " -- " + requestMethod + " body:"); for (Map.Entry<String, String> entry : request.getParams().entrySet()) sb.append("\n\t").append(entry.getKey()).append(":").append(entry.getValue()); logger.log(Level.INFO, sb.toString()); getRequestQueue().add(request); }
From source file:com.gargoylesoftware.htmlunit.UrlFetchWebConnection.java
/** * {@inheritDoc}/*from www . j a va2 s. c om*/ */ @Override public WebResponse getResponse(final WebRequest webRequest) throws IOException { final long startTime = System.currentTimeMillis(); final URL url = webRequest.getUrl(); if (LOG.isTraceEnabled()) { LOG.trace("about to fetch URL " + url); } // hack for JS, about, and data URLs. final WebResponse response = produceWebResponseForGAEProcolHack(url); if (response != null) { return response; } // this is a "normal" URL try { final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // connection.setUseCaches(false); connection.setConnectTimeout(webClient_.getOptions().getTimeout()); connection.addRequestProperty("User-Agent", webClient_.getBrowserVersion().getUserAgent()); connection.setInstanceFollowRedirects(false); // copy the headers from WebRequestSettings for (final Entry<String, String> header : webRequest.getAdditionalHeaders().entrySet()) { connection.addRequestProperty(header.getKey(), header.getValue()); } addCookies(connection); final HttpMethod httpMethod = webRequest.getHttpMethod(); connection.setRequestMethod(httpMethod.name()); if (HttpMethod.POST == httpMethod || HttpMethod.PUT == httpMethod || HttpMethod.PATCH == httpMethod) { connection.setDoOutput(true); final String charset = webRequest.getCharset(); connection.addRequestProperty("Content-Type", FormEncodingType.URL_ENCODED.getName()); try (final OutputStream outputStream = connection.getOutputStream()) { final List<NameValuePair> pairs = webRequest.getRequestParameters(); final org.apache.http.NameValuePair[] httpClientPairs = NameValuePair.toHttpClient(pairs); final String query = URLEncodedUtils.format(Arrays.asList(httpClientPairs), charset); outputStream.write(query.getBytes(charset)); if (webRequest.getRequestBody() != null) { IOUtils.write(webRequest.getRequestBody().getBytes(charset), outputStream); } } } final int responseCode = connection.getResponseCode(); if (LOG.isTraceEnabled()) { LOG.trace("fetched URL " + url); } final List<NameValuePair> headers = new ArrayList<>(); for (final Map.Entry<String, List<String>> headerEntry : connection.getHeaderFields().entrySet()) { final String headerKey = headerEntry.getKey(); if (headerKey != null) { // map contains entry like (null: "HTTP/1.1 200 OK") final StringBuilder sb = new StringBuilder(); for (final String headerValue : headerEntry.getValue()) { if (sb.length() != 0) { sb.append(", "); } sb.append(headerValue); } headers.add(new NameValuePair(headerKey, sb.toString())); } } final byte[] byteArray; try (final InputStream is = responseCode < 400 ? connection.getInputStream() : connection.getErrorStream()) { byteArray = IOUtils.toByteArray(is); } final long duration = System.currentTimeMillis() - startTime; final WebResponseData responseData = new WebResponseData(byteArray, responseCode, connection.getResponseMessage(), headers); saveCookies(url.getHost(), headers); return new WebResponse(responseData, webRequest, duration); } catch (final IOException e) { LOG.error("Exception while tyring to fetch " + url, e); throw new RuntimeException(e); } }
From source file:com.grouzen.android.serenity.HttpConnection.java
private HttpResponse get(String url, Bundle params) throws ClientProtocolException, IOException { String urlParametrized = url; if (params != null) { urlParametrized += "?" + URLEncodedUtils.format(convertParams(params), CHARSET); }//from www .ja va2 s .c o m return execute(new HttpGet(urlParametrized)); }
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 w ww. j av 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:cn.org.eshow.framwork.http.AbRequestParams.java
/** * ??.//from w w w . j a v a 2 s . com * * @return the param string */ public String getParamString() { List<BasicNameValuePair> paramsList = new LinkedList<BasicNameValuePair>(); for (ConcurrentHashMap.Entry<String, String> entry : urlParams.entrySet()) { paramsList.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } return URLEncodedUtils.format(paramsList, HTTP.UTF_8); }
From source file:com.foobnix.api.vkontakte.VkOld.java
public static List<VkAudio> searchAll(String text, Context context) throws VKAuthorizationException { List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("q", text)); params.add(new BasicNameValuePair("count", "100")); params.add(new BasicNameValuePair("access_token", Pref.getStr(context, Pref.VKONTAKTE_TOKEN))); String paramsList = URLEncodedUtils.format(params, "UTF-8"); HttpGet request = new HttpGet(API_URL + "audio.search?" + paramsList); HttpClient client = new DefaultHttpClient(); HttpResponse response;/*from w ww .j a va2 s.c o m*/ List<VkAudio> result = null; try { response = client.execute(request); HttpEntity entity = response.getEntity(); String jString = EntityUtils.toString(entity); if (jString.contains("error_code")) { throw new VKAuthorizationException("VK connection Erorr"); } LOG.d(jString); result = JSONHelper.parseVKSongs(jString); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } return result; }
From source file:org.n52.sos.service.it.SosV1IT.java
/** * Send a V1 GetCapabilities request via GET and verify the response * /* ww w. j a v a 2s . c o m*/ * @throws IOException * @throws URISyntaxException * @throws IllegalStateException * @throws XmlException * @throws SAXException */ @Ignore @Test public void getCapabilitiesV1Get() throws IOException, URISyntaxException, IllegalStateException, XmlException, SAXException { List<NameValuePair> qparams = getBaseQueryParams(); qparams.add(new BasicNameValuePair("request", SosConstants.Operations.GetCapabilities.name())); qparams.add(new BasicNameValuePair("acceptVersions", Sos1Constants.SERVICEVERSION)); HttpGet request = new HttpGet(getSOSURI(URLEncodedUtils.format(qparams, "UTF-8"))); verifyCapabilitiesV1(request); }