List of usage examples for org.apache.http.client.entity UrlEncodedFormEntity setContentEncoding
public void setContentEncoding(Header header)
From source file:com.lostad.app.base.util.RequestUtil.java
public static String putForm(String url, List<NameValuePair> params, String token, boolean isSingleton) throws Exception { String json = null;//from w w w . j a va 2s . com HttpClient client = HttpClientManager.getHttpClient(isSingleton); HttpEntity resEntity = null; HttpPut put = new HttpPut(url); put.addHeader("token", token); try { put.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); if (params != null) { UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8); if (params != null) { entity.setContentEncoding(HTTP.UTF_8); entity.setContentType("application/x-www-form-urlencoded"); } put.setEntity(entity); } HttpResponse response = client.execute(put, new BasicHttpContext()); resEntity = response.getEntity(); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 200 // ? json = EntityUtils.toString(resEntity); } } catch (Exception e) { if (put != null) { put.abort();// } throw e; } finally { if (resEntity != null) { try { resEntity.consumeContent();//? } catch (IOException e) { e.printStackTrace(); } } client.getConnectionManager().closeExpiredConnections(); ///client.getConnectionManager().shutdown(); } return json; }
From source file:org.grameenfoundation.consulteca.utils.HttpHelpers.java
public static InputStream postDataRequestAndGetStream(String url, UrlEncodedFormEntity formEntity, String contentType, int networkTimeout) throws IllegalStateException, ClientProtocolException, IOException { HttpParams httpParameters = HttpHelpers.getConnectionParameters(networkTimeout); HttpClient httpClient = new DefaultHttpClient(httpParameters); HttpPost httpPost = new HttpPost(url); HttpHelpers.addCommonHeaders(httpPost); formEntity.setContentType(contentType); formEntity.setContentEncoding(HTTP.UTF_8); httpPost.setEntity(formEntity);/*w ww . j a v a 2 s .com*/ httpPost.addHeader("HTTP-Version", "HTTP/1.0"); httpPost.addHeader("Accept-Encoding", "gzip"); httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset = UTF-8"); HttpResponse res = httpClient.execute(httpPost); return getInputStream(res); }
From source file:me.Aron.Heinecke.fbot.lib.Socket.java
/*** * Performs the login into fronter based on the DB credentials * Requires the tokens form getReqID//from w w w. j a v a 2s . co m * @return site content */ public synchronized String login() throws ClientProtocolException, IOException { String url = "https://fronter.com/giessen/index.phtml"; //create client & post HttpPost post = new HttpPost(url); // add header post.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); post.setHeader("Accept-Encoding", "gzip, deflate"); post.setHeader("Accept-Language", "de-de,de;q=0.8,en-us;q=0.5,en;q=0.3"); post.setHeader("Connection", "keep-alive"); post.setHeader("DNT", "1"); post.setHeader("Host", "fronter.com"); post.setHeader("Referer", "https://fronter.com/giessen/index.phtml"); post.setHeader("User-Agent", UA); // set login parameters & fake normal login data List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(); urlParameters.add(new BasicNameValuePair("SSO_COMMAND", "")); urlParameters.add(new BasicNameValuePair("SSO_COMMAND_SECHASH", fbot.getDB().getSSOCOM())); urlParameters.add(new BasicNameValuePair("USER_INITIAL_SCREEN_HEIGH...", "1080")); urlParameters.add(new BasicNameValuePair("USER_INITIAL_SCREEN_WIDTH", "1920")); urlParameters.add(new BasicNameValuePair("USER_INITIAL_WINDOW_HEIGH...", "914")); urlParameters.add(new BasicNameValuePair("USER_INITIAL_WINDOW_WIDTH", "1920")); urlParameters.add(new BasicNameValuePair("USER_SCREEN_SIZE", "")); urlParameters.add(new BasicNameValuePair("chp", "")); urlParameters.add(new BasicNameValuePair("fronter_request_token", fbot.getDB().getReqtoken())); urlParameters.add(new BasicNameValuePair("mainurl", "main.phtml")); urlParameters.add(new BasicNameValuePair("newlang", "de")); urlParameters.add(new BasicNameValuePair("password", fbot.getDB().getPass())); urlParameters.add(new BasicNameValuePair("saveid", "-1")); urlParameters.add(new BasicNameValuePair("username", fbot.getDB().getUser())); //create gzip encoder UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(urlParameters); urlEncodedFormEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_ENCODING, "UTF_8")); post.setEntity(urlEncodedFormEntity); //Create own context which stores the cookies HttpClientContext context = HttpClientContext.create(); HttpResponse response = client.execute(post, context); if (fbot.isDebug()) { fbot.getLogger().debug("socket", "Sending POST request to URL: " + url); fbot.getLogger().debug("socket", "Response code: " + response.getStatusLine().getStatusCode()); fbot.getLogger().log("debug", "socket", context.getCookieStore().getCookies()); } // input-stream with gzip-accept InputStream input = response.getEntity().getContent(); InputStreamReader isr = new InputStreamReader(input); BufferedReader rd = new BufferedReader(isr); StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) { result.append(line); } input.close(); isr.close(); rd.close(); fbot.getDB().setCookieStore(context.getCookieStore()); return result.toString(); }
From source file:com.mozilla.simplepush.simplepushdemoapp.MainActivity.java
/** Send the notification to SimplePush * * This is normally what the App Server would do. We're handling it ourselves because * this app is self-contained.// ww w . j a v a2 s . co m * * @param data the notification string. */ private void SendNotification(final String data) { if (PushEndpoint.length() == 0) { return; } // Run as a background task, passing the data string and getting a success bool. new AsyncTask<String, Void, Boolean>() { @Override protected Boolean doInBackground(String... params) { HttpPut req = new HttpPut(PushEndpoint); // HttpParams is NOT what you use here. // NameValuePairs is just a simple hash. List<NameValuePair> rparams = new ArrayList<>(2); rparams.add(new BasicNameValuePair("version", String.valueOf(System.currentTimeMillis()))); // While we're just using a simple string here, there's no reason you couldn't // have this be up to 4K of JSON. Just make sure that the GcmIntentService handler // knows what to do with it. rparams.add(new BasicNameValuePair("data", data)); Log.i(TAG, "Sending data: " + data); try { UrlEncodedFormEntity entity = new UrlEncodedFormEntity(rparams); Log.i(TAG, "params:" + rparams.toString() + " entity: " + entity.toString()); entity.setContentType("application/x-www-form-urlencoded"); entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "text/plain;charset=UTF-8")); req.setEntity(entity); req.addHeader("Authorization", genSignature(entity)); DefaultHttpClient client = new DefaultHttpClient(); HttpResponse resp = client.execute(req); int code = resp.getStatusLine().getStatusCode(); if (code >= 200 && code < 300) { return true; } } catch (ClientProtocolException x) { Log.e(TAG, "Could not send Notification " + x); } catch (IOException x) { Log.e(TAG, "Could not send Notification (io) " + x); } catch (Exception e) { Log.e(TAG, "flaming crapsticks", e); } return false; } /** Report back on what just happened. * * @param success Status of post execution */ @Override protected void onPostExecute(Boolean success) { String msg = "was"; if (!success) { msg = "was not"; } mDisplay.setText("Message " + msg + " sent"); } }.execute(data, null, null); }
From source file:com.yunmall.ymsdk.net.http.RequestParams.java
private HttpEntity createFormEntity() { try {// w w w .j av a 2s.co m UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(getParamsList(), contentEncoding); urlEncodedFormEntity.setContentType( new BasicHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")); urlEncodedFormEntity.setContentEncoding(contentEncoding); return urlEncodedFormEntity; } catch (UnsupportedEncodingException e) { YmLog.e(LOG_TAG, "createFormEntity failed", e); return null; // Can happen, if the 'contentEncoding' won't be HTTP.UTF_8 } }
From source file:com.groupon.odo.client.Client.java
protected String doPost(String apiUrl, BasicNameValuePair[] data) throws Exception { String fullUrl = BASE_URL + apiUrl; HttpPost post = new HttpPost(fullUrl); post.setHeader("Content-Type", "application/x-www-form-urlencoded"); ArrayList<BasicNameValuePair> dataList = new ArrayList<BasicNameValuePair>(); if (data != null) { dataList.addAll(Arrays.asList(data)); }/*from www .java 2 s . c o m*/ // add clientUUID if necessary if (_clientId != null) { BasicNameValuePair clientPair = new BasicNameValuePair("clientUUID", _clientId); dataList.add(clientPair); } if (dataList.size() > 0) { UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(dataList); urlEncodedFormEntity.setContentEncoding(HTTP.UTF_8); post.setEntity(urlEncodedFormEntity); } HttpClient client = new DefaultHttpClient(); HttpConnectionParams.setConnectionTimeout(client.getParams(), _timeout); HttpConnectionParams.setSoTimeout(client.getParams(), _timeout); HttpResponse response = client.execute(post); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String accumulator = ""; String line = ""; while ((line = rd.readLine()) != null) { accumulator += line; accumulator += "\n"; } return accumulator; }
From source file:se.su.dsv.scipro.android.json.SciProJSON.java
private String getJson(String uri, List<NameValuePair> postParams) { String result = ""; HttpPost httpPost = new HttpPost(uri); String contentType = "application/json"; try {/*from www . j a va2 s .c o m*/ UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams); entity.setContentEncoding(HTTP.UTF_8); httpPost.setEntity(entity); httpPost.setHeader("Accept", contentType); } catch (UnsupportedEncodingException e) { Log.e(TAG, "UnsupportedEncodingException: " + e); } try { HttpResponse httpResponse = httpClient.execute(httpPost, new BasicHttpContext()); HttpEntity httpEntity = httpResponse.getEntity(); if (httpEntity != null) { InputStream is = httpEntity.getContent(); result = StringUtils.convertStreamToString(is); } } catch (ClientProtocolException e) { Log.e(TAG, "ClientProtocolException: ", e); } catch (IOException e) { Log.e(TAG, "IOException: ", e); } return result; }
From source file:st.geekli.api.GeeklistApi.java
private Object internalDoRequest(String url, HashMap<String, Object> params, HttpMethod method, boolean sign) throws GeeklistApiException { HttpRequestBase request = null;/*from www. j av a 2 s . c o m*/ GeeklistApi.debugOut("Request", method.toString() + " " + url + " " + params.toString() + " | sign=" + sign); switch (method) { case GET: StringBuilder sb = new StringBuilder(); sb.append(url); if (params.size() > 0) { sb.append("?"); for (Iterator<Map.Entry<String, Object>> i = params.entrySet().iterator(); i.hasNext();) { Map.Entry<String, Object> param = i.next(); try { sb.append(param.getKey()); sb.append('='); sb.append(URLEncoder.encode(param.getValue().toString(), "UTF-8")); if (i.hasNext()) sb.append('&'); } catch (UnsupportedEncodingException e) { throw new GeeklistApiException(e); } } } request = new HttpGet(sb.toString()); break; case POST: request = new HttpPost(url); request.setHeader("Content-Type", "application/x-www-form-urlencoded"); ArrayList<BasicNameValuePair> postParams = new ArrayList<BasicNameValuePair>(); if (params.size() > 0) { for (Map.Entry<String, Object> param : params.entrySet()) { postParams.add(new BasicNameValuePair(param.getKey(), param.getValue().toString())); } } UrlEncodedFormEntity urlEncodedFormEntity; try { urlEncodedFormEntity = new UrlEncodedFormEntity(postParams); urlEncodedFormEntity.setContentEncoding(HTTP.UTF_8); ((HttpPost) request).setEntity(urlEncodedFormEntity); } catch (UnsupportedEncodingException e2) { throw new GeeklistApiException(e2); } break; } request.setHeader("User-Agent", mUserAgent); request.setHeader("Accept-Charset", "UTF-8"); if (sign) { try { mOAuthConsumer.sign(request); } catch (OAuthMessageSignerException e1) { throw new GeeklistApiException(e1); } catch (OAuthExpectationFailedException e1) { throw new GeeklistApiException(e1); } catch (OAuthCommunicationException e1) { throw new GeeklistApiException(e1); } } try { HttpResponse response = mClient.execute(request); GeeklistApi.debugOut("Response-Code", Integer.toString(response.getStatusLine().getStatusCode())); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK || response.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN || response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { JSONObject responseObject = new JSONObject( Utils.inputStreamToString(response.getEntity().getContent())); if (responseObject.optString("status").equals("ok")) { JSONObject obj = responseObject.optJSONObject("data"); if (obj != null) { return obj; } else { return responseObject.optJSONArray("data"); } } else { throw new GeeklistApiException(responseObject.optString("error")); } } else { GeeklistApi.debugOut("Failed body length", "" + response.getEntity().getContentLength()); response.getEntity().consumeContent(); throw new GeeklistApiException(response.getStatusLine().getReasonPhrase()); } } catch (ClientProtocolException e) { throw new GeeklistApiException(e); } catch (IOException e) { throw new GeeklistApiException(e); } catch (IllegalStateException e) { throw new GeeklistApiException(e); } catch (JSONException e) { throw new GeeklistApiException(e); } }