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:longism.com.api.APIUtils.java
/** * TODO Function:Load json by type.<br> * * @param activity - to get context// w w w . java 2s.co m * @param action - get or post or s.thing else. Define at top of class * @param data - Parameter * @param url - host of API * @param apiCallBack - call back to handle action when start, finish, success or fail * @param username - username if sever need to log in * @param password - password if sever need to log in * @date: July 07, 2015 * @author: Nguyen Long */ public static void LoadJSONByType(final Activity activity, final int action, final HashMap<String, String> data, final String url, final String username, final String password, final APICallBack apiCallBack) { activity.runOnUiThread(new Runnable() { @Override public void run() { apiCallBack.uiStart(); } }); new Thread(new Runnable() { @Override public synchronized void run() { try { HttpGet get = null; HttpPost post = null; HttpResponse response = null; String paramString = null; ArrayList<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>(); if (data != null) { Set<String> set = data.keySet(); for (String key : set) { BasicNameValuePair value = new BasicNameValuePair(key, data.get(key)); list.add(value); } } HttpParams params = new BasicHttpParams(); HttpConnectionParams.setSoTimeout(params, TIMEOUT_TIME); HttpConnectionParams.setConnectionTimeout(params, TIMEOUT_TIME); DefaultHttpClient client = new DefaultHttpClient(params); /** * Select action to do */ switch (action) { case ACTION_GET_JSON: paramString = URLEncodedUtils.format(list, "utf-8"); get = new HttpGet(url + "?" + paramString); response = client.execute(get); break; case ACTION_POST_JSON: post = new HttpPost(url); post.setEntity(new UrlEncodedFormEntity(list, "UTF-8")); response = client.execute(post); break; case ACTION_GET_JSON_WITH_AUTH: paramString = URLEncodedUtils.format(list, "utf-8"); get = new HttpGet(url + "?" + paramString); setAuthenticate(client, get, username, password); response = client.execute(get); break; case ACTION_POST_JSON_WITH_AUTH: post = new HttpPost(url); post.setEntity(new UrlEncodedFormEntity(list, "UTF-8")); setAuthenticate(client, post, username, password); response = client.execute(post); break; } final StringBuilder builder = new StringBuilder(); if (response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { InputStream inputStream = response.getEntity().getContent(); Scanner scanner = new Scanner(inputStream); while (scanner.hasNext()) { builder.append(scanner.nextLine()); } inputStream.close(); scanner.close(); apiCallBack.success(builder.toString(), 0); } else { apiCallBack.fail(response != null && response.getStatusLine() != null ? "response null" : "" + response.getStatusLine().getStatusCode()); } } catch (final Exception e) { apiCallBack.fail(e.getMessage()); } finally { activity.runOnUiThread(new Runnable() { @Override public void run() { apiCallBack.uiEnd(); } }); } } }).start(); }
From source file:org.mobicents.servlet.sip.restcomm.interpreter.tagstrategy.sms.SmsTagStrategy.java
private void handleSmsMessage(final boolean success) { if (success) { sms = sms.setDateSent(DateTime.now()).setStatus(SmsMessage.Status.SENT); } else {//from w w w. ja va2 s . co m sms = sms.setStatus(SmsMessage.Status.FAILED); } final SmsMessagesDao dao = daos.getSmsMessagesDao(); dao.updateSmsMessage(sms); if (statusCallback != null) { final List<NameValuePair> parameters = context.getRcmlRequestParameters(); parameters.add(new BasicNameValuePair("SmsSid", sms.getSid().toString())); parameters.add(new BasicNameValuePair("SmsStatus", sms.getStatus().toString())); try { final HttpRequestExecutor executor = new HttpRequestExecutor(); final HttpRequestDescriptor request = new HttpRequestDescriptor(statusCallback, "POST", parameters); executor.execute(request); } catch (final UnsupportedEncodingException exception) { } catch (final URISyntaxException exception) { interpreter.notify(context, Notification.WARNING, 14105, statusCallback, "POST", URLEncodedUtils.format(parameters, "UTF-8"), null, null); } catch (final ClientProtocolException exception) { interpreter.notify(context, Notification.ERROR, 11206, statusCallback, "POST", URLEncodedUtils.format(parameters, "UTF-8"), null, null); } catch (final IllegalArgumentException exception) { } catch (final IOException exception) { interpreter.notify(context, Notification.ERROR, 11200, statusCallback, "POST", URLEncodedUtils.format(parameters, "UTF-8"), null, null); } } }
From source file:fm.krui.kruifm.TwitterManager.java
/** * Returns the (public) timeline of a specific user. * @param screenName Username of account to get timeline (with or without leading @) * @param tweetCount Number of tweets to pull as an integer * @param trimUser true to strip user objects down to only user id, false to return full user object. *//*from w ww . j av a2 s.c o m*/ public void getTimeline(String screenName, int tweetCount, boolean trimUser) { // URL Parameter constants final String SCREEN_NAME = "screen_name"; final String TWEET_COUNT = "count"; final String TRIM_USER = "trim_user"; String url = ROOT_URL + TIMELINE_URL + "?"; String username = validateUsername(screenName); // Encode POST parameters in the URL List<NameValuePair> params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair(SCREEN_NAME, username)); params.add(new BasicNameValuePair(TWEET_COUNT, Integer.toString(tweetCount))); if (trimUser) { params.add(new BasicNameValuePair(TRIM_USER, Integer.toString(1))); } String paramString = URLEncodedUtils.format(params, "UTF-8"); url += paramString; // Build connection environment and execute String userAgent = "Android"; //FIXME: Use more specific identifier here AndroidHttpClient androidHttpClient = AndroidHttpClient.newInstance(userAgent); HttpGet httpGet = new HttpGet(url); // Build listener HTTPConnectionListener localListener = new HTTPConnectionListener() { @Override public void onConnectionFinish(String result) { callback.onConnectionFinish(result); } }; // Apply authorization header with bearer token httpGet.setHeader("Authorization", "Bearer " + bearerToken); Log.v(TAG, "Set Authentication Header using bearerToken " + bearerToken); new HTTPConnection(androidHttpClient, httpGet, localListener).execute(); }
From source file:com.smartling.api.sdk.BaseApiClientAdapter.java
protected String buildParamsQuery(final NameValuePair... nameValuePairs) { final List<NameValuePair> qparams = getRequiredParams(); for (final NameValuePair nameValuePair : nameValuePairs) if (nameValuePair.getValue() != null) qparams.add(nameValuePair);// ww w .j ava2 s . co m return URLEncodedUtils.format(qparams, CharEncoding.UTF_8); }
From source file:ch.entwine.weblounge.common.impl.util.TestUtils.java
/** * Issues the the given request./*from ww w .ja v a 2s .co m*/ * * @param httpClient * the http client * @param request * the request * @param params * the request parameters * @throws Exception * if the request fails */ public static HttpResponse request(HttpClient httpClient, HttpUriRequest request, String[][] params) throws Exception { if (params != null) { if (request instanceof HttpGet) { List<NameValuePair> qparams = new ArrayList<NameValuePair>(); if (params.length > 0) { for (String[] param : params) { if (param.length < 2) continue; qparams.add(new BasicNameValuePair(param[0], param[1])); } } URI requestURI = request.getURI(); URI uri = URIUtils.createURI(requestURI.getScheme(), requestURI.getHost(), requestURI.getPort(), requestURI.getPath(), URLEncodedUtils.format(qparams, "utf-8"), null); HeaderIterator headerIterator = request.headerIterator(); request = new HttpGet(uri); while (headerIterator.hasNext()) { request.addHeader(headerIterator.nextHeader()); } } else if (request instanceof HttpPost) { List<NameValuePair> formparams = new ArrayList<NameValuePair>(); for (String[] param : params) formparams.add(new BasicNameValuePair(param[0], param[1])); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "utf-8"); ((HttpPost) request).setEntity(entity); } else if (request instanceof HttpPut) { List<NameValuePair> formparams = new ArrayList<NameValuePair>(); for (String[] param : params) formparams.add(new BasicNameValuePair(param[0], param[1])); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "utf-8"); ((HttpPut) request).setEntity(entity); } } else { if (request instanceof HttpPost || request instanceof HttpPut) { UrlEncodedFormEntity entity = new UrlEncodedFormEntity(new ArrayList<NameValuePair>(), "utf-8"); ((HttpEntityEnclosingRequestBase) request).setEntity(entity); } } return httpClient.execute(request); }
From source file:com.httprequest.HTTPRequest.java
/** * Send synchronous request to HTTP server. * /*from ww w . j a v a 2 s.c o m*/ * @param method request method (GET or POST). * @param params set of pairs <key, value>, fields. * @param listenr interface (callback) to bind to external classes. * @return response of HTTP Server. */ private String HTTPSyncRequest(Methods method, JSONObject params, OnHTTPRequest listenr) { Log.i(LOG_TAG, "HTTPSyncRequest(" + method + ")"); List<NameValuePair> requestParams = null; HttpRequestBase httpRequest = null; OnHTTPRequest listener = listenr; try { requestParams = jsonToList(params); } catch (JSONException e1) { e1.printStackTrace(); } // Set parameters of HTTP request. HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, connectionTimeout); HttpConnectionParams.setSoTimeout(httpParameters, socketTimeout); // Create a new HttpClient and Header HttpClient httpclient = new DefaultHttpClient(httpParameters); if (method == Methods.GET) { httpRequest = new HttpGet(URLServer + "?" + URLEncodedUtils.format(requestParams, "utf-8")); } else { httpRequest = new HttpPost(URLServer); // Add data to request try { ((HttpPost) httpRequest).setEntity(new UrlEncodedFormEntity(requestParams)); } catch (UnsupportedEncodingException e) { listener.OnResquestError(e.getMessage().toString()); e.printStackTrace(); } } try { // Execute HTTP Post Request HttpResponse response = httpclient.execute(httpRequest); Log.i(LOG_TAG, "Code: " + response.getStatusLine().getStatusCode()); // Response if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { return getHTTPResponseContent(response); } else { listener.OnResquestError("Server Error"); } } catch (SocketTimeoutException e) { listener.OnResquestError("Socket Timeout" + e.getMessage().toString()); Log.e(LOG_TAG, "Socket Timeout", e); } catch (ConnectTimeoutException e) { listener.OnResquestError("Connect Timeout" + e.getMessage().toString()); Log.e(LOG_TAG, "Connect Timeout", e); } catch (ClientProtocolException e) { listener.OnResquestError("HTTP Error: " + e.getMessage().toString()); Log.e(LOG_TAG, "HTTP Error", e); } catch (IOException e) { listener.OnResquestError("Connection Error: " + e.getMessage().toString()); Log.e(LOG_TAG, "Connection Error", e); } return null; }
From source file:fi.iki.murgo.irssinotifier.Server.java
private static String buildUrlWithParameters(String url, Map<String, String> parameters) { if (!url.endsWith("?")) url += "?"; List<NameValuePair> params = new ArrayList<NameValuePair>(); for (Entry<String, String> entry : parameters.entrySet()) { params.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); }//from w w w. j av a 2 s . c o m String paramString = URLEncodedUtils.format(params, "utf-8"); url += paramString; return url; }
From source file:com.iloomo.net.RequestParams.java
/** * ??? * @return ? */ protected String getParamString() { return URLEncodedUtils.format(getParamsList(), ENCODING); }
From source file:es.trigit.gitftask.Conexion.Http.java
/** * Performs http DELETE petition to server. * * @param url URL to perform DELETE petition. * @param parameters Parameters to include in petition. * * @return Response from the server.// www. ja v a 2s .c o m * @throws IOException If the <tt>parameters</tt> have errors, connection timed out, * socket timed out or other error related with the connection occurs. */ public static HttpResponse delete(String url, ArrayList<NameValuePair> parameters) throws IOException { HttpParams httpParameters = new BasicHttpParams(); int timeoutConnection = 10000; HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); int timeoutSocket = 10000; HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); HttpClient httpclient = new DefaultHttpClient(httpParameters); if (parameters != null) { String paramString = URLEncodedUtils.format(parameters, "utf-8"); url += "?" + paramString; } HttpDelete httpdelete = new HttpDelete(url); HttpResponse response = httpclient.execute(httpdelete); return response; }
From source file:com.liferay.petra.json.web.service.client.BaseJSONWebServiceClientImpl.java
@Override public String doDelete(String url, Map<String, String> parameters, Map<String, String> headers) throws JSONWebServiceInvocationException, JSONWebServiceTransportException { if (!isNull(_contextPath)) { url = _contextPath + url;//ww w . j a v a2 s. c o m } List<NameValuePair> nameValuePairs = toNameValuePairs(parameters); if (!nameValuePairs.isEmpty()) { String queryString = URLEncodedUtils.format(nameValuePairs, _CHARSET); url += "?" + queryString; } if (_logger.isDebugEnabled()) { _logger.debug("Sending DELETE request to " + _login + "@" + _hostName + url); log("HTTP headers", headers); log("HTTP parameters", parameters); } HttpDelete httpDelete = new HttpDelete(url); addHeaders(httpDelete, headers); return execute(httpDelete); }