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.megam.api.http.TransportMachinery.java
public static TransportResponse get(TransportTools nuts) throws URISyntaxException, ClientProtocolException, IOException { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(nuts.urlString()); if (nuts.headers() != null) { for (Map.Entry<String, String> headerEntry : nuts.headers().entrySet()) { //this if condition is set for twilio Rest API to add credentials to DefaultHTTPClient, conditions met twilio work. if (headerEntry.getKey().equalsIgnoreCase("provider") & headerEntry.getValue().equalsIgnoreCase(nuts.headers().get("provider"))) { httpclient.getCredentialsProvider().setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials( nuts.headers().get("account_sid"), nuts.headers().get("oauth_token"))); }/*from w w w .ja v a 2 s. com*/ //this else part statements for other providers else { httpget.addHeader(headerEntry.getKey(), headerEntry.getValue()); } } } if (nuts.isQuery()) { URIBuilder uribuilder = new URIBuilder(nuts.urlString()); uribuilder.setQuery(URLEncodedUtils.format(nuts.pairs(), nuts.encoding())); httpget.setURI(uribuilder.build()); } TransportResponse transportResp = null; try { HttpResponse httpResp = httpclient.execute(httpget); transportResp = new TransportResponse(httpResp.getStatusLine(), httpResp.getEntity(), httpResp.getLocale()); } finally { httpget.releaseConnection(); } return transportResp; }
From source file:org.thomnichols.android.gmarks.BookmarksQueryService.java
public void login(String user, String passwd) { try {/* ww w . j a va 2 s . c o m*/ List<NameValuePair> queryParams = new ArrayList<NameValuePair>(); queryParams.add(new BasicNameValuePair("service", "bookmarks")); queryParams.add(new BasicNameValuePair("passive", "true")); queryParams.add(new BasicNameValuePair("nui", "1")); queryParams.add(new BasicNameValuePair("continue", "https://www.google.com/bookmarks/l")); queryParams.add(new BasicNameValuePair("followup", "https://www.google.com/bookmarks/l")); HttpGet get = new HttpGet( "https://www.google.com/accounts/ServiceLogin?" + URLEncodedUtils.format(queryParams, "UTF-8")); HttpResponse resp = http.execute(get, this.ctx); // this just gets the cookie but I can ignore it... if (resp.getStatusLine().getStatusCode() != 200) throw new RuntimeException( "Invalid status code for ServiceLogin " + resp.getStatusLine().getStatusCode()); resp.getEntity().consumeContent(); String galx = null; for (Cookie c : cookieStore.getCookies()) if (c.getName().equals("GALX")) galx = c.getValue(); if (galx == null) throw new RuntimeException("GALX cookie not found!"); HttpPost loginMethod = new HttpPost("https://www.google.com/accounts/ServiceLoginAuth"); // post parameters: List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("Email", user)); nvps.add(new BasicNameValuePair("Passwd", passwd)); nvps.add(new BasicNameValuePair("PersistentCookie", "yes")); nvps.add(new BasicNameValuePair("GALX", galx)); nvps.add(new BasicNameValuePair("continue", "https://www.google.com/bookmarks/l")); loginMethod.setEntity(new UrlEncodedFormEntity(nvps)); resp = http.execute(loginMethod, this.ctx); if (resp.getStatusLine().getStatusCode() != 302) throw new RuntimeException( "Unexpected status code for ServiceLoginAuth" + resp.getStatusLine().getStatusCode()); resp.getEntity().consumeContent(); Header checkCookieLocation = resp.getFirstHeader("Location"); if (checkCookieLocation == null) throw new RuntimeException("Missing checkCookie redirect location!"); // CheckCookie: get = new HttpGet(checkCookieLocation.getValue()); resp = http.execute(get, this.ctx); if (resp.getStatusLine().getStatusCode() != 302) throw new RuntimeException( "Unexpected status code for CheckCookie" + resp.getStatusLine().getStatusCode()); resp.getEntity().consumeContent(); this.authInitialized = true; Log.i(TAG, "Final redirect location: " + resp.getFirstHeader("Location").getValue()); Log.i(TAG, "Logged in."); } catch (IOException ex) { Log.e(TAG, "Error during login", ex); throw new RuntimeException("IOException during login", ex); } }
From source file:org.jboss.as.test.integration.jsf.doctype.DoctypeDeclTestCase.java
private String register(String name, int expectedStatusCode) throws Exception { DefaultHttpClient client = new DefaultHttpClient(); try {//from w w w .j a v a2s . com // Create and execute a GET request String jsfViewState = null; String requestUrl = url.toString() + "register.jsf"; HttpGet getRequest = new HttpGet(requestUrl); HttpResponse response = client.execute(getRequest); try { // Get the JSF view state String responseString = IOUtils.toString(response.getEntity().getContent(), "UTF-8"); Matcher jsfViewMatcher = viewStatePattern.matcher(responseString); if (jsfViewMatcher.find()) { jsfViewState = jsfViewMatcher.group(1); } } finally { HttpClientUtils.closeQuietly(response); } // Create and execute a POST request with the given name HttpPost post = new HttpPost(requestUrl); List<NameValuePair> list = new ArrayList<NameValuePair>(); list.add(new BasicNameValuePair("javax.faces.ViewState", jsfViewState)); list.add(new BasicNameValuePair("register", "register")); list.add(new BasicNameValuePair("register:inputName", name)); list.add(new BasicNameValuePair("register:registerButton", "Register")); post.setEntity(new StringEntity(URLEncodedUtils.format(list, "UTF-8"), ContentType.APPLICATION_FORM_URLENCODED)); response = client.execute(post); try { assertEquals(expectedStatusCode, response.getStatusLine().getStatusCode()); return IOUtils.toString(response.getEntity().getContent(), "UTF-8"); } finally { HttpClientUtils.closeQuietly(response); } } finally { HttpClientUtils.closeQuietly(client); } }
From source file:gr.ntua.ivml.awareness.search.SearchServiceAccess.java
private URI constructURIRecord(String recid) { URI uri = null;/* w w w . j a v a 2 s. c o m*/ List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("wskey", "api2demo")); try { uri = URIUtils.createURI("http", "preview.europeana.eu", 80, "/api/v2/record" + recid + ".json", URLEncodedUtils.format(qparams, "UTF-8"), null); } catch (URISyntaxException e) { e.printStackTrace(); } return uri; }
From source file:com.csipsimple.plugins.betamax.CallHandlerWeb.java
@Override public void onReceive(Context context, Intent intent) { if (Utils.ACTION_GET_PHONE_HANDLERS.equals(intent.getAction())) { PendingIntent pendingIntent = null; // Extract infos from intent received String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER); // Extract infos from settings SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); String user = prefs.getString(CallHandlerConfig.KEY_TW_USER, ""); String pwd = prefs.getString(CallHandlerConfig.KEY_TW_PWD, ""); String nbr = prefs.getString(CallHandlerConfig.KEY_TW_NBR, ""); String provider = prefs.getString(CallHandlerConfig.KEY_TW_PROVIDER, ""); // We must handle that clean way cause when call just to // get the row in account list expect this to reply correctly if (!TextUtils.isEmpty(number) && !TextUtils.isEmpty(user) && !TextUtils.isEmpty(nbr) && !TextUtils.isEmpty(pwd) && !TextUtils.isEmpty(provider)) { // Build pending intent Intent i = new Intent(ACTION_DO_WEB_CALL); i.setClass(context, getClass()); i.putExtra(Intent.EXTRA_PHONE_NUMBER, number); pendingIntent = PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT); }//from w w w.j a v a 2 s.c o m // Build icon Bitmap bmp = Utils.getBitmapFromResource(context, R.drawable.icon_web); // Build the result for the row (label, icon, pending intent, and // excluded phone number) Bundle results = getResultExtras(true); if (pendingIntent != null) { results.putParcelable(Utils.EXTRA_REMOTE_INTENT_TOKEN, pendingIntent); } // Text for the row String providerName = ""; Resources r = context.getResources(); if (!TextUtils.isEmpty(provider)) { String[] arr = r.getStringArray(R.array.provider_values); String[] arrEntries = r.getStringArray(R.array.provider_entries); int i = 0; for (String prov : arr) { if (prov.equalsIgnoreCase(provider)) { providerName = arrEntries[i]; break; } i++; } } results.putString(Intent.EXTRA_TITLE, providerName + " " + r.getString(R.string.web_callback)); Log.d(THIS_FILE, "icon is " + bmp); if (bmp != null) { results.putParcelable(Intent.EXTRA_SHORTCUT_ICON, bmp); } // DO *NOT* exclude from next tel: intent cause we use a http method // results.putString(Intent.EXTRA_PHONE_NUMBER, number); } else if (ACTION_DO_WEB_CALL.equals(intent.getAction())) { // Extract infos from intent received String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER); // Extract infos from settings SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); String user = prefs.getString(CallHandlerConfig.KEY_TW_USER, ""); String pwd = prefs.getString(CallHandlerConfig.KEY_TW_PWD, ""); String nbr = prefs.getString(CallHandlerConfig.KEY_TW_NBR, ""); String provider = prefs.getString(CallHandlerConfig.KEY_TW_PROVIDER, ""); // params List<NameValuePair> params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("username", user)); params.add(new BasicNameValuePair("password", pwd)); params.add(new BasicNameValuePair("from", nbr)); params.add(new BasicNameValuePair("to", number)); String paramString = URLEncodedUtils.format(params, "utf-8"); String requestURL = "https://www." + provider + "/myaccount/makecall.php?" + paramString; HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(requestURL); // Create a response handler HttpResponse httpResponse; try { httpResponse = httpClient.execute(httpGet); Log.d(THIS_FILE, "response code is " + httpResponse.getStatusLine().getStatusCode()); if (httpResponse.getStatusLine().getStatusCode() == 200) { InputStreamReader isr = new InputStreamReader(httpResponse.getEntity().getContent()); BufferedReader br = new BufferedReader(isr); String line; String fullReply = ""; boolean foundSuccess = false; while ((line = br.readLine()) != null) { if (!TextUtils.isEmpty(line) && line.toLowerCase().contains("success")) { showToaster(context, "Success... wait a while you'll called back"); foundSuccess = true; break; } if (!TextUtils.isEmpty(line)) { fullReply = fullReply.concat(line); } } if (!foundSuccess) { showToaster(context, "Error : server error : " + fullReply); } } else { showToaster(context, "Error : invalid request " + httpResponse.getStatusLine().getStatusCode()); } } catch (ClientProtocolException e) { showToaster(context, "Error : " + e.getLocalizedMessage()); } catch (IOException e) { showToaster(context, "Error : " + e.getLocalizedMessage()); } } }
From source file:com.sugestio.client.SugestioClient.java
/** * Performs a GET request and returns the response body as a JsonElement. * @param resource the resource to get/*from ww w . ja v a2 s . c o m*/ * @param parameters query string parameters * @param raise404 if true, a HTTP response of 404 will raise an exception, if false, the method will return null * @return JsonElement * @throws Exception */ private JsonElement doGet(String resource, Map<String, String> parameters, boolean raise404) throws Exception { HttpClient httpClient = new DefaultHttpClient(); String uri = getUri(resource); if (parameters != null && parameters.size() > 0) { List<NameValuePair> queryParams = new ArrayList<NameValuePair>(); for (String key : parameters.keySet()) { queryParams.add(new BasicNameValuePair(key, parameters.get(key))); } uri += "?" + URLEncodedUtils.format(queryParams, "UTF-8"); } try { HttpGet httpGet = new HttpGet(uri); HttpResponse httpResponse = httpClient.execute(httpGet); String body = EntityUtils.toString(httpResponse.getEntity()); int code = httpResponse.getStatusLine().getStatusCode(); if (code == 200) { httpClient.getConnectionManager().shutdown(); JsonParser parser = new JsonParser(); return parser.parse(body); } else if (code == 404 && !raise404) { httpClient.getConnectionManager().shutdown(); return null; } else { String message = "Response code " + httpResponse.getStatusLine().getStatusCode() + ". "; message += body; throw new Exception(message); } } catch (Exception e) { httpClient.getConnectionManager().shutdown(); throw e; } }
From source file:org.onsteroids.eve.api.connector.http.PooledHttpApiConnection.java
@Override public XmlApiResult call(final String xmlPath, final ApiKey key, final Map<String, String> parameters) throws ApiException { if (httpClient == null) { initializeHttpClient();/*from w w w . j ava 2 s .c o m*/ } Preconditions.checkNotNull(xmlPath, "XmlPath"); LOG.debug("Requesting {}...", xmlPath); try { // build query List<NameValuePair> qparams = Lists.newArrayList(); if (key != null) { LOG.trace("Using ApiKey {}", key); qparams.add(new BasicNameValuePair("userID", Long.toString(key.getUserId()))); qparams.add(new BasicNameValuePair("apiKey", key.getApiKey())); } if (parameters != null) { LOG.trace("Using parameters: {}", parameters); for (Map.Entry<String, String> entry : parameters.entrySet()) { qparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } } final URI requestURI = URIUtils.createURI(serverUri.getScheme(), serverUri.getHost(), serverUri.getPort(), xmlPath, URLEncodedUtils.format(qparams, "UTF-8"), null); LOG.trace("Resulting URI: {}", requestURI); final HttpPost postRequest = new HttpPost(requestURI); // make the real call LOG.trace("Fetching result from {}...", serverUri); final HttpResponse response = httpClient.execute(postRequest); final InputStream stream = response.getEntity().getContent(); // parse the xml final DocumentBuilder builder = builderFactory.newDocumentBuilder(); final Document doc = builder.parse(stream); // process the xml return apiCoreParser.call(doc, xmlPath, key, parameters, serverUri); } catch (ApiException e) { throw e; } catch (Exception e) { throw new InternalApiException(e); } }
From source file:org.mahasen.client.Delete.java
/** * @param fileName/* w w w . ja v a2s.c o m*/ * @throws IOException */ public void delete(String fileName) throws IOException, MahasenClientException, URISyntaxException { httpclient = new DefaultHttpClient(); try { String userName = clientLoginData.getUserName(); String passWord = clientLoginData.getPassWord(); String hostAndPort = clientLoginData.getHostNameAndPort(); String userId = clientLoginData.getUserId(userName, passWord); Boolean isLogged = clientLoginData.isLoggedIn(); System.out.println(" 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 { httpclient.getConnectionManager().shutdown(); } }
From source file:org.gdg.frisbee.android.api.GroupDirectory.java
public ApiRequest getChapterEventList(final DateTime start, final DateTime end, final String chapterId, Response.Listener<ArrayList<Event>> successListener, Response.ErrorListener errorListener) { ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new NameValuePair() { @Override/* w ww . jav a2s. co m*/ public String getName() { return "group"; } @Override public String getValue() { return chapterId; } }); params.add(new NameValuePair() { @Override public String getName() { return "start"; } @Override public String getValue() { return "" + (int) (start.getMillis() / 1000); } }); if (end != null) { params.add(new NameValuePair() { @Override public String getName() { return "end"; } @Override public String getValue() { return "" + (int) (end.getMillis() / 1000); } }); } params.add(new NameValuePair() { @Override public String getName() { return "_"; } @Override public String getValue() { return "" + (int) (new DateTime().getMillis() / 1000); } }); Type type = new TypeToken<ArrayList<Event>>() { }.getType(); String url = CHAPTER_CALENDAR_URL; url += "?" + URLEncodedUtils.format(params, "UTF-8"); GsonRequest<Void, ArrayList<Event>> eventReq = new GsonRequest<Void, ArrayList<Event>>(Request.Method.GET, url, type, successListener, errorListener, GsonRequest.getGson(FieldNamingPolicy.IDENTITY)); return new ApiRequest(eventReq); }
From source file:org.mahasen.client.Download.java
public void download(String fileName, String downloadRepo) throws IOException, MahasenClientException, URISyntaxException { httpclient = new DefaultHttpClient(); OutputStream outputStream = null; try {// w ww. ja va 2s. c o m String userName = clientLoginData.getUserName(); String passWord = clientLoginData.getPassWord(); String hostAndPort = clientLoginData.getHostNameAndPort(); String userId = clientLoginData.getUserId(userName, passWord); Boolean isLogged = clientLoginData.isLoggedIn(); System.out.println(" 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/download_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 httpEntity = response.getEntity(); if (httpEntity.getContentLength() > 0) { outputStream = new FileOutputStream(downloadRepo + "/" + fileName); httpEntity.writeTo(outputStream); } else { System.out.println("no content available"); } System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (httpEntity != null) { System.out.println("Response content length: " + httpEntity.getContentLength()); System.out.println("Chunked?: " + httpEntity.isChunked()); } EntityUtils.consume(httpEntity); 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(); } }