List of usage examples for org.apache.http.client.entity UrlEncodedFormEntity UrlEncodedFormEntity
public UrlEncodedFormEntity(final Iterable<? extends NameValuePair> parameters, final Charset charset)
From source file:ch.ralscha.extdirectspring_itest.UserControllerTest.java
@Test public void testPostWithErrors() throws IOException { Locale.setDefault(Locale.ENGLISH); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("extTID", "2")); formparams.add(new BasicNameValuePair("extAction", "userController")); formparams.add(new BasicNameValuePair("extMethod", "updateUser")); formparams.add(new BasicNameValuePair("extType", "rpc")); formparams.add(new BasicNameValuePair("extUpload", "false")); formparams.add(new BasicNameValuePair("name", "Joe")); formparams.add(new BasicNameValuePair("age", "30")); UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(formparams, "UTF-8"); this.post.setEntity(postEntity); CloseableHttpResponse response = this.client.execute(this.post); try {//from w w w.j av a2 s .c o m HttpEntity entity = response.getEntity(); assertThat(entity).isNotNull(); String responseString = EntityUtils.toString(entity); Map<String, Object> rootAsMap = this.mapper.readValue(responseString, Map.class); assertThat(rootAsMap).hasSize(5); assertThat(rootAsMap.get("method")).isEqualTo("updateUser"); assertThat(rootAsMap.get("type")).isEqualTo("rpc"); assertThat(rootAsMap.get("action")).isEqualTo("userController"); assertThat(rootAsMap.get("tid")).isEqualTo(2); Map<String, Object> result = (Map<String, Object>) rootAsMap.get("result"); assertThat(result).hasSize(4); assertThat(result.get("name")).isEqualTo("Joe"); assertThat(result.get("age")).isEqualTo(30); assertThat(result.get("success")).isEqualTo(Boolean.FALSE); Map<String, Object> errors = (Map<String, Object>) result.get("errors"); assertThat(errors).hasSize(1); assertThat((List<String>) errors.get("email")).containsOnly("may not be empty"); } finally { IOUtils.closeQuietly(response); } }
From source file:net.networksaremadeofstring.rhybudd.ZenossAPICore.java
@Override public boolean Login(ZenossCredentials credentials) throws Exception { if (credentials.URL.contains("https://")) { this.PrepareSSLHTTPClient(); } else {/*from ww w . j a va2 s . c o m*/ this.PrepareHTTPClient(); //httpclient = new DefaultHttpClient(); } if (!credentials.BAUser.equals("") || !credentials.BAPassword.equals("")) { //Log.i("Auth","We have some auth credentials"); CredentialsProvider credProvider = new BasicCredentialsProvider(); credProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(credentials.BAUser, credentials.BAPassword)); httpclient.setCredentialsProvider(credProvider); } HttpPost httpost = new HttpPost(credentials.URL + "/zport/acl_users/cookieAuthHelper/login"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("__ac_name", credentials.UserName)); nvps.add(new BasicNameValuePair("__ac_password", credentials.Password)); nvps.add(new BasicNameValuePair("submitted", "true")); nvps.add(new BasicNameValuePair("came_from", credentials.URL + "/zport/dmd")); httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); // Response from POST not needed, just the cookie HttpResponse response = httpclient.execute(httpost); // Consume so we can reuse httpclient response.getEntity().consumeContent(); //Set the variables for later this.ZENOSS_INSTANCE = credentials.URL; this.ZENOSS_USERNAME = credentials.UserName; this.ZENOSS_PASSWORD = credentials.Password; Log.e("CheckLoggedIn", Integer.toString(response.getStatusLine().getStatusCode())); reqCount++; return this.CheckLoggedIn(); }
From source file:edu.emory.library.utils.EULHttpUtils.java
/** * Utility method to POST to a URL and read the result into a string * @param url url to be read//from w ww . j a v a2 s .c o m * @param headers HashMap of request headers * @param parameters HashMap of parameters */ public static String postUrlContents(String url, HashMap<String, String> headers, HashMap<String, String> parameters) throws Exception { String response = null; HttpClient client = new DefaultHttpClient(); HttpPost postMethod = new HttpPost(url); // add any request headers specified for (Map.Entry<String, String> header : headers.entrySet()) { postMethod.addHeader(header.getKey(), header.getValue()); } List<NameValuePair> nvps = new ArrayList<NameValuePair>(); for (Map.Entry<String, String> param : parameters.entrySet()) { nvps.add(new BasicNameValuePair(param.getKey(), param.getValue())); } postMethod.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); ResponseHandler<String> responseHandler = new BasicResponseHandler(); // returns the response content as string on success response = client.execute(postMethod, responseHandler); // could throw HttpException or IOException // TODO: catch/handle errors (esp. periodic 503 when Spotlight is unavailable) postMethod.releaseConnection(); return response; }
From source file:com.allwinner.theatreplayer.launcher.service.UpdateService.java
private void sendPost(String server_url) { // Log.v(TAG, "send post to server"); HttpPost post = new HttpPost(server_url); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("guid", "646212C46B774f95BBBE2F9CCFF32797")); params.add(new BasicNameValuePair("service_type", "APK_UPDATE")); params.add(new BasicNameValuePair("para_serial", Utils.rcId)); HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setSoTimeout(httpParameters, Utils.CHECK_TIMEOUT); HttpClient httpClient = new DefaultHttpClient(httpParameters); try {/*from w ww .j a v a 2 s .co m*/ post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); HttpResponse response = httpClient.execute(post); if (response.getStatusLine().getStatusCode() == 200) { HttpEntity entity = response.getEntity(); String data = EntityUtils.toString(entity, "UTF-8"); Utils.saveUpdateJson(data, Utils.sdcardPathQQ + "/update.json"); JSONObject jsonobj = new JSONObject(data); int version = jsonobj.getInt("version"); // Log.i(TAG, "?md5 = "+jsonobj.getString("md5")); // Log.i(TAG, "version = "+version); // Log.i(TAG, "local = "+Utils.getVersionCode(this)); // Log.i(TAG, "url = "+jsonobj.getString("url")); if (version > Utils.getVersionCode(this)) { // Intent intent = new Intent(); intent.setAction(APKONCHECKED); sendBroadcast(intent); } } else { Log.i(TAG, "1: response status: " + response.getStatusLine().getStatusCode()); } } catch (Exception e) { Log.i(TAG, "Exception ERROR_UNKNOWN" + e.getMessage()); } }
From source file:testingproject.TestingProjectDLB.java
static List<String> getDLBResults(String lotteryCode, String date) throws UnsupportedEncodingException, IOException { // 16/11/17 map.put("1", "Makara"); map.put("2", "Kumba"); map.put("3", "meena"); map.put("4", "mesha"); map.put("5", "wrushabha"); map.put("6", "mithuna"); map.put("7", "kataka"); map.put("8", "sinha"); map.put("9", "kanya"); map.put("10", "thula"); map.put("11", "dhanu"); map.put("12", "Thula"); HttpClient httpclient = HttpClients.createDefault(); HttpPost httppost = new HttpPost( "http://dlb.today/dlb/index.php?option=com_jumi&fileid=31&Itemid=31"); // Request parameters and other properties. List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>(2); params.add(new BasicNameValuePair("db", lotteryCode)); params.add(new BasicNameValuePair("dn", "")); params.add(new BasicNameValuePair("ename", date)); httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); //Execute and get the response. HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); try {// w ww. ja v a2 s . c o m String content = convertStreamToString(instream); //System.out.println(content); List<String> dataList = getData(content); // for (String data : dataList) { // System.out.println(data); // } return dataList; } finally { instream.close(); } } return null; }
From source file:hu.sztaki.lpds.dcibridge.util.io.HttpHandler.java
public InputStream getStream(Hashtable<String, String> pValue) throws IOException { List<NameValuePair> nvps = new ArrayList<NameValuePair>(); Enumeration<String> enm = pValue.keys(); String key;/*ww w . ja v a2 s. c o m*/ while (enm.hasMoreElements()) { key = enm.nextElement(); nvps.add(new BasicNameValuePair(key, pValue.get(key))); } httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); HttpResponse response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); return entity.getContent(); }
From source file:org.whispercomm.c2dm4j.impl.C2dmHttpPost.java
private void initPostEntity(Message message) { List<NameValuePair> params = new ArrayList<NameValuePair>(); addParam(params, REGISTRATION_ID, message.getRegistrationId()); addParam(params, COLLAPSE_ID, message.getCollapseKey()); if (message.delayWhileIdle()) addParam(params, DELAY_WHILE_IDLE); Map<String, String> data = message.getData(); for (String key : data.keySet()) { addParam(params, DATA_KEY_PREFIX + key, data.get(key)); }//from w ww . java 2 s.c o m try { this.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); } catch (UnsupportedEncodingException e) { /* * This should not be a checked exception. Good testing will catch * if an unsupported encoding is requested. */ throw new RuntimeException(e.getMessage(), e); } }
From source file:eu.earthobservatory.org.StrabonEndpoint.client.SPARQLEndpoint.java
/** * Executes a SPARQL query on the Endpoint and get the results * in the format specified by stSPARQLQueryResultFormat, which is * an instance of class (or a subclass) {@link TupleQueryResultFormat}. * /*from ww w . ja v a 2s .co m*/ * @param sparqlQuery * @param format * @return * @throws IOException */ public EndpointResult query(String sparqlQuery, stSPARQLQueryResultFormat format) throws IOException { assert (format != null); // create a post method to execute HttpPost method = new HttpPost(getConnectionURL()); // set the query parameter List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("query", sparqlQuery)); UrlEncodedFormEntity encodedEntity = new UrlEncodedFormEntity(params, Charset.defaultCharset()); method.setEntity(encodedEntity); // set the content type method.setHeader("Content-Type", "application/x-www-form-urlencoded"); // set the accept format method.addHeader("Accept", format.getDefaultMIMEType()); try { // response that will be filled next String responseBody = ""; // execute the method HttpResponse response = hc.execute(method); int statusCode = response.getStatusLine().getStatusCode(); // If the response does not enclose an entity, there is no need // to worry about connection release HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(instream)); StringBuffer strBuf = new StringBuffer(); // do something useful with the response String nextLine; while ((nextLine = reader.readLine()) != null) { strBuf.append(nextLine + "\n"); } // remove last newline character if (strBuf.length() > 0) { strBuf.setLength(strBuf.length() - 1); } responseBody = strBuf.toString(); } catch (IOException ex) { // In case of an IOException the connection will be released // back to the connection manager automatically throw ex; } catch (RuntimeException ex) { // In case of an unexpected exception you may want to abort // the HTTP request in order to shut down the underlying // connection and release it back to the connection manager. method.abort(); throw ex; } finally { // Closing the input stream will trigger connection release instream.close(); } } return new EndpointResult(statusCode, response.getStatusLine().getReasonPhrase(), responseBody); } catch (IOException e) { throw e; } finally { // release the connection. method.releaseConnection(); } }
From source file:org.apache.jena.atlas.web.auth.FormLogin.java
/** * Gets the HTTP Entity for the Login request * //from w ww.j a v a 2 s . c o m * @return Login request entity * @throws UnsupportedEncodingException * Thrown if the platform does not support UTF-8 */ public HttpEntity getLoginEntity() throws UnsupportedEncodingException { List<NameValuePair> nvps = new ArrayList<>(); nvps.add(new BasicNameValuePair(this.loginUserField, this.username)); nvps.add(new BasicNameValuePair(this.loginPasswordField, new String(this.password))); return new UrlEncodedFormEntity(nvps, "UTF-8"); }
From source file:org.dataconservancy.archive.impl.fcrepo.ri.RIClient.java
private InputStream executeQuery(String sparql, boolean flush) { HttpPost post = new HttpPost(riEndpoint); List<NameValuePair> args = new ArrayList<NameValuePair>(); if (flush) {/* ww w.j a va 2s .c o m*/ args.add(new BasicNameValuePair("flush", "true")); } args.add(new BasicNameValuePair("type", "tuples")); args.add(new BasicNameValuePair("lang", "sparql")); args.add(new BasicNameValuePair("format", "Simple")); args.add(new BasicNameValuePair("stream", "on")); args.add(new BasicNameValuePair("query", sparql)); try { post.setEntity(new UrlEncodedFormEntity(args, HTTP.UTF_8)); } catch (UnsupportedEncodingException wontHappen) { throw new RuntimeException(wontHappen); } try { HttpResponse response = httpClient.execute(post); int responseCode = response.getStatusLine().getStatusCode(); if (responseCode != 200) { throw new RuntimeException( "Fedora Resource Index query " + "returned an unexpected HTTP response code: " + responseCode + ". Consult Fedora Server log for " + "details."); } HttpEntity entity = response.getEntity(); if (entity == null) { return new ByteArrayInputStream(new byte[0]); } else { return entity.getContent(); } } catch (IOException e) { throw new RuntimeException(e); } }