List of usage examples for org.apache.http.protocol HTTP UTF_8
String UTF_8
To view the source code for org.apache.http.protocol HTTP UTF_8.
Click Source Link
From source file:com.prey.net.PreyRestHttpClient.java
public PreyHttpResponse put(String url, Map<String, String> params, PreyConfig preyConfig) throws IOException { HttpPut method = new HttpPut(url); method.setHeader("Accept", "*/*"); method.setEntity(new UrlEncodedFormEntity(getHttpParamsFromMap(params), HTTP.UTF_8)); // method.setParams(getHttpParamsFromMap(params)); PreyLogger.d("Sending using 'PUT' - URI: " + url + " - parameters: " + params.toString()); HttpResponse httpResponse = httpclient.execute(method); PreyHttpResponse response = new PreyHttpResponse(httpResponse); //PreyLogger.d("Response from server: " + response.toString()); return response; }
From source file:com.kkbox.toolkit.internal.api.APIRequest.java
public void addFilePostParam(String path) { fileEntity = new FileEntity(new File(path), URLEncodedUtils.CONTENT_TYPE + HTTP.CHARSET_PARAM + HTTP.UTF_8); }
From source file:com.lgallardo.youtorrentcontroller.JSONParser.java
public JSONObject getJSONFromUrl(String url) throws JSONParserStatusCodeException { // if server is publish in a subfolder, fix url if (subfolder != null && !subfolder.equals("")) { url = subfolder + "/" + url; }//from w w w . j a v a2s . c om HttpResponse httpResponse; DefaultHttpClient httpclient; HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. // The default value is zero, that means the timeout is not used. int timeoutConnection = connection_timeout * 1000; // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = data_timeout * 1000; // Set http parameters HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); HttpProtocolParams.setUserAgent(httpParameters, "youTorrent Controller"); HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8); // Making HTTP request HttpHost targetHost = new HttpHost(this.hostname, this.port, this.protocol); // httpclient = new DefaultHttpClient(httpParameters); // httpclient = new DefaultHttpClient(); httpclient = getNewHttpClient(); // Set http parameters httpclient.setParams(httpParameters); try { AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password); httpclient.getCredentialsProvider().setCredentials(authScope, credentials); // set http parameters url = protocol + "://" + hostname + ":" + port + "/" + url + token; // Log.d("Debug", "getJSONFromUrl - url: " + url); // Log.d("Debug", "getJSONFromUrl - cookie: " + cookie); HttpGet httpget = new HttpGet(url); if (this.cookie != null) { httpget.setHeader("Cookie", this.cookie); } httpResponse = httpclient.execute(targetHost, httpget); StatusLine statusLine = httpResponse.getStatusLine(); int mStatusCode = statusLine.getStatusCode(); if (mStatusCode != 200) { httpclient.getConnectionManager().shutdown(); throw new JSONParserStatusCodeException(mStatusCode); } HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); // Build JSON BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); json = sb.toString(); // try parse the string to a JSON object jObj = new JSONObject(json); } catch (JSONException e) { Log.e("Debug", "getJSONFromUrl - JSONException - Error parsing data " + e.toString()); } catch (UnsupportedEncodingException e) { Log.e("Debug", "getJSONFromUrl - UnsupportedEncodingException: " + e.toString()); } catch (ClientProtocolException e) { Log.e("Debug", "getJSONFromUrl - ClientProtocolException: " + e.toString()); e.printStackTrace(); } catch (IOException e) { Log.e("Debug", "getJSONFromUrl - IOException: " + e.toString()); // e.printStackTrace(); httpclient.getConnectionManager().shutdown(); throw new JSONParserStatusCodeException(TIMEOUT_ERROR); } catch (JSONParserStatusCodeException e) { httpclient.getConnectionManager().shutdown(); throw new JSONParserStatusCodeException(e.getCode()); } catch (Exception e) { Log.e("Debug", "getJSONFromUrl - Generic: " + e.toString()); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } // return JSON String return jObj; }
From source file:com.phonty.improved.Rates.java
public boolean get(String country) { Log.e("RESPONSE", "Start getting"); String line = null;//from w w w . j a v a2 s . c o m StringBuilder builder = new StringBuilder(); try { String locale = context.getResources().getConfiguration().locale.getCountry(); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("country", country)); nvps.add(new BasicNameValuePair("locale", locale)); httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); HttpResponse response = client.execute(httppost); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200) { HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); while ((line = reader.readLine()) != null) { builder.append(line); Log.e("RESPONSE", line); if (parse(line) != null) return true; else return false; } } else { } } catch (ClientProtocolException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } return false; }
From source file:mobisocial.metrics.UsageMetrics.java
public void report(String feature, String value) { if (mLevel == ReportingLevel.DISABLED || UsageMetrics.CHIRP_REPORTING_ENDPOINT == null) { return;/*from w w w . j a v a 2s . co m*/ } Message msg = mReportingThread.mHandler.obtainMessage(ReportingHandler.HTTP_REQUEST); HttpPost post = new HttpPost(UsageMetrics.CHIRP_REPORTING_ENDPOINT); List<NameValuePair> data = new ArrayList<NameValuePair>(); JSONObject json = jsonForReport(feature); try { json.put("feature", feature); json.put("value", value); } catch (JSONException e) { } data.add(new BasicNameValuePair("json", json.toString())); try { post.setEntity(new UrlEncodedFormEntity(data, HTTP.UTF_8)); msg.obj = post; mReportingThread.mHandler.sendMessage(msg); } catch (IOException e) { } }
From source file:org.zaizi.oauth2utils.OAuthUtils.java
public static String getAccessToken(OAuth2Details oauthDetails) { HttpPost post = new HttpPost(oauthDetails.getAuthenticationServerUrl()); String clientId = oauthDetails.getClientId(); String clientSecret = oauthDetails.getClientSecret(); String scope = oauthDetails.getScope(); List<BasicNameValuePair> parametersBody = new ArrayList<BasicNameValuePair>(); parametersBody.add(new BasicNameValuePair(OAuthConstants.GRANT_TYPE, oauthDetails.getGrantType())); parametersBody.add(new BasicNameValuePair(OAuthConstants.USERNAME, oauthDetails.getUsername())); parametersBody.add(new BasicNameValuePair(OAuthConstants.PASSWORD, oauthDetails.getPassword())); if (isValid(clientId)) { parametersBody.add(new BasicNameValuePair(OAuthConstants.CLIENT_ID, clientId)); }// ww w .jav a 2 s .co m if (isValid(clientSecret)) { parametersBody.add(new BasicNameValuePair(OAuthConstants.CLIENT_SECRET, clientSecret)); } if (isValid(scope)) { parametersBody.add(new BasicNameValuePair(OAuthConstants.SCOPE, scope)); } DefaultHttpClient client = new DefaultHttpClient(); HttpResponse response = null; String accessToken = null; try { post.setEntity(new UrlEncodedFormEntity(parametersBody, HTTP.UTF_8)); response = client.execute(post); int code = response.getStatusLine().getStatusCode(); if (code >= 400) { System.out.println("Authorization server expects Basic authentication"); // Add Basic Authorization header post.addHeader(OAuthConstants.AUTHORIZATION, getBasicAuthorizationHeader(oauthDetails.getUsername(), oauthDetails.getPassword())); System.out.println("Retry with login credentials"); post.releaseConnection(); response = client.execute(post); code = response.getStatusLine().getStatusCode(); if (code >= 400) { System.out.println("Retry with client credentials"); post.removeHeaders(OAuthConstants.AUTHORIZATION); post.addHeader(OAuthConstants.AUTHORIZATION, getBasicAuthorizationHeader( oauthDetails.getClientId(), oauthDetails.getClientSecret())); post.releaseConnection(); response = client.execute(post); code = response.getStatusLine().getStatusCode(); if (code >= 400) { throw new RuntimeException( "Could not retrieve access token for user: " + oauthDetails.getUsername()); } } } Map<String, String> map = handleResponse(response); accessToken = map.get(OAuthConstants.ACCESS_TOKEN); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return accessToken; }
From source file:cn.com.loopj.android.http.MySSLSocketFactory.java
/** * Gets a DefaultHttpClient which trusts a set of certificates specified by the KeyStore * * @param keyStore custom provided KeyStore instance * @return DefaultHttpClient//from w ww . j ava 2 s .c o m */ public static DefaultHttpClient getNewHttpClient(KeyStore keyStore) { try { SSLSocketFactory sf = new MySSLSocketFactory(keyStore); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", sf, 443)); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); return new DefaultHttpClient(ccm, params); } catch (Exception e) { return new DefaultHttpClient(); } }
From source file:com.mobicage.rogerthat.registration.AbstractRegistrationWizard.java
protected void sendInstallationId(final MainService mainService) { if (mInstallationId == null) { throw new IllegalStateException("Installation id should be set!"); }//from ww w. j ava2 s.c om new SafeAsyncTask<Object, Object, Boolean>() { @SuppressWarnings("unchecked") @Override protected Boolean safeDoInBackground(Object... params) { try { HttpClient httpClient = HTTPUtil.getHttpClient(10000, 3); final HttpPost httpPost = HTTPUtil.getHttpPost(mainService, CloudConstants.REGISTRATION_REGISTER_INSTALL_URL); List<NameValuePair> formParams = HTTPUtil.getRegistrationFormParams(mainService); formParams.add(new BasicNameValuePair("version", MainService.getVersion(mainService))); formParams.add(new BasicNameValuePair("install_id", getInstallationId())); UrlEncodedFormEntity entity; try { entity = new UrlEncodedFormEntity(formParams, HTTP.UTF_8); } catch (UnsupportedEncodingException e) { L.bug(e); return true; } httpPost.setEntity(entity); L.d("Sending installation id: " + getInstallationId()); try { HttpResponse response = httpClient.execute(httpPost); L.d("Installation id sent"); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { L.e("HTTP request resulted in status code " + statusCode); return false; } HttpEntity httpEntity = response.getEntity(); if (httpEntity == null) { L.e("Response of '" + CloudConstants.REGISTRATION_REGISTER_INSTALL_URL + "' was null"); return false; } final Map<String, Object> responseMap = (Map<String, Object>) JSONValue .parse(new InputStreamReader(httpEntity.getContent())); if (responseMap == null) { L.e("HTTP request responseMap was null"); return false; } if (!"success".equals(responseMap.get("result"))) { L.e("HTTP request result was not 'success' but: " + responseMap.get("result")); return false; } return true; } catch (ClientProtocolException e) { L.bug(e); return false; } catch (IOException e) { L.bug(e); return false; } } catch (Exception e) { L.bug(e); return false; } } }.execute(); }
From source file:com.klinker.android.twitter.utils.api_helper.TwitLongerHelper.java
/** * Posts the status to twitlonger//from w w w . ja v a 2 s .c o m * @return returns an object containing the shortened text and the id for the twitlonger url */ public TwitLongerStatus postToTwitLonger() { try { HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(POST_URL); post.addHeader("X-API-KEY", TWITLONGER_API_KEY); post.addHeader("X-Auth-Service-Provider", SERVICE_PROVIDER); post.addHeader("X-Verify-Credentials-Authorization", getAuthrityHeader(twitter)); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("content", tweetText)); if (replyToId != 0) { nvps.add(new BasicNameValuePair("reply_to_id", String.valueOf(replyToId))); } else if (replyToScreenname != null) { nvps.add(new BasicNameValuePair("reply_to_screen_name", replyToScreenname)); } post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); HttpResponse response = client.execute(post); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line; String content = ""; String id = ""; StringBuilder builder = new StringBuilder(); while ((line = rd.readLine()) != null) { builder.append(line); } try { // there is only going to be one thing returned ever JSONObject jsonObject = new JSONObject(builder.toString()); content = jsonObject.getString("tweet_content"); id = jsonObject.getString("id"); } catch (Exception e) { e.printStackTrace(); } Log.v("talon_twitlonger", "content: " + content); Log.v("talon_twitlonger", "id: " + id); return new TwitLongerStatus(content, id); } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:com.iia.giveastick.util.RestClient.java
public String invoke(Verb verb, String path, JSONObject jsonParams, List<Header> headers) throws Exception { //EncodingTypes charset=serviceContext.getCharset(); long startTime = 0, endTime = 0; String result = null;// w w w . ja v a 2s .c o m this.statusCode = 404; HttpResponse response = null; HttpHost targetHost = new HttpHost(this.serviceName, this.port, this.scheme); //HttpEntity entity = this.buildMultipartEntity(params); HttpEntity entity = null; if (jsonParams != null && jsonParams.has("file")) { entity = this.buildMultipartEntity(jsonParams); } else { entity = this.buildJsonEntity(jsonParams); } HttpRequest request = this.buildHttpRequest(verb, path, entity, headers); if (this.login != null && this.password != null) { request.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials(this.login, this.password), "UTF-8", false)); } if (!TextUtils.isEmpty(this.CSRFtoken)) { request.addHeader("X-CSRF-Token", this.CSRFtoken); } try { if (debugWeb) { startTime = System.currentTimeMillis(); } response = this.httpClient.execute(targetHost, request); this.statusCode = response.getStatusLine().getStatusCode(); this.readHeader(response); if (debugWeb) { endTime = System.currentTimeMillis(); } // we assume that the response body contains the error message HttpEntity resultEntity = response.getEntity(); if (resultEntity != null) { result = EntityUtils.toString(resultEntity, HTTP.UTF_8); } if (debugWeb && GiveastickApplication.DEBUG) { final long endTime2 = System.currentTimeMillis(); //System.out.println( // "The REST response is:\n " + serviceResponse); Log.d(TAG, "Time taken in REST operation : " + (endTime - startTime) + " ms. => [" + verb + "]" + path); Log.d(TAG, "Time taken in service response construction : " + (endTime2 - endTime) + " ms."); } } catch (ConnectTimeoutException e) { Log.e(TAG, "Connection timed out. The host may be unreachable."); e.printStackTrace(); throw new Exception(e.getMessage()); } catch (IOException e) { Log.e(TAG, e.getCause().getMessage()); throw new Exception(e.getMessage()); } catch (Exception e) { e.printStackTrace(); throw e; } finally { this.httpClient.getConnectionManager().shutdown(); } return result; }