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:cn.com.zhenshiyin.crowd.net.AsyncHttpPost.java
@Override public void run() { String ret = ""; try {/*from w ww . jav a 2 s . c o m*/ request = new HttpPost(url); if (Constants.isGzip) { request.addHeader("Accept-Encoding", "gzip"); } else { request.addHeader("Accept-Encoding", "default"); } LogUtil.d(AsyncHttpPost.class.getName(), "AsyncHttpPost request to url :" + url); if (parameter != null && parameter.size() > 0) { List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>(); for (RequestParameter p : parameter) { list.add(new BasicNameValuePair(p.getName(), p.getValue())); } ((HttpPost) request).setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8)); } httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeout); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, readTimeout); HttpResponse response = httpClient.execute(request); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { InputStream is = response.getEntity().getContent(); BufferedInputStream bis = new BufferedInputStream(is); bis.mark(2); // ?? byte[] header = new byte[2]; int result = bis.read(header); // reset?? bis.reset(); // ?GZIP? int headerData = getShort(header); // Gzip ? ? 0x1f8b if (result != -1 && headerData == 0x1f8b) { LogUtil.d("HttpTask", " use GZIPInputStream "); is = new GZIPInputStream(bis); } else { LogUtil.d("HttpTask", " not use GZIPInputStream"); is = bis; } InputStreamReader reader = new InputStreamReader(is, "utf-8"); char[] data = new char[100]; int readSize; StringBuffer sb = new StringBuffer(); while ((readSize = reader.read(data)) > 0) { sb.append(data, 0, readSize); } ret = sb.toString(); bis.close(); reader.close(); } else { RequestException exception = new RequestException(RequestException.IO_EXCEPTION, "??,??" + statusCode); ret = ErrorUtil.errorJson("ERROR.HTTP.001", exception.getMessage()); } LogUtil.d(AsyncHttpPost.class.getName(), "AsyncHttpPost request to url :" + url + " finished !"); } catch (java.lang.IllegalArgumentException e) { RequestException exception = new RequestException(RequestException.IO_EXCEPTION, Constants.ERROR_MESSAGE); ret = ErrorUtil.errorJson("ERROR.HTTP.002", exception.getMessage()); LogUtil.d(AsyncHttpGet.class.getName(), "AsyncHttpPost request to url :" + url + " onFail " + e.getMessage()); } catch (org.apache.http.conn.ConnectTimeoutException e) { RequestException exception = new RequestException(RequestException.SOCKET_TIMEOUT_EXCEPTION, Constants.ERROR_MESSAGE); ret = ErrorUtil.errorJson("ERROR.HTTP.003", exception.getMessage()); LogUtil.d(AsyncHttpPost.class.getName(), "AsyncHttpPost request to url :" + url + " onFail " + e.getMessage()); } catch (java.net.SocketTimeoutException e) { RequestException exception = new RequestException(RequestException.SOCKET_TIMEOUT_EXCEPTION, Constants.ERROR_MESSAGE); ret = ErrorUtil.errorJson("ERROR.HTTP.004", exception.getMessage()); LogUtil.d(AsyncHttpPost.class.getName(), "AsyncHttpPost request to url :" + url + " onFail " + e.getMessage()); } catch (UnsupportedEncodingException e) { RequestException exception = new RequestException(RequestException.UNSUPPORTED_ENCODEING_EXCEPTION, "?"); ret = ErrorUtil.errorJson("ERROR.HTTP.005", exception.getMessage()); LogUtil.d(AsyncHttpPost.class.getName(), "AsyncHttpPost request to url :" + url + " UnsupportedEncodingException " + e.getMessage()); } catch (org.apache.http.conn.HttpHostConnectException e) { RequestException exception = new RequestException(RequestException.CONNECT_EXCEPTION, ""); ret = ErrorUtil.errorJson("ERROR.HTTP.006", exception.getMessage()); LogUtil.d(AsyncHttpPost.class.getName(), "AsyncHttpPost request to url :" + url + " HttpHostConnectException " + e.getMessage()); } catch (ClientProtocolException e) { RequestException exception = new RequestException(RequestException.CLIENT_PROTOL_EXCEPTION, "??"); ret = ErrorUtil.errorJson("ERROR.HTTP.007", exception.getMessage()); e.printStackTrace(); LogUtil.d(AsyncHttpPost.class.getName(), "AsyncHttpPost request to url :" + url + " ClientProtocolException " + e.getMessage()); } catch (IOException e) { RequestException exception = new RequestException(RequestException.IO_EXCEPTION, "??"); ret = ErrorUtil.errorJson("ERROR.HTTP.008", exception.getMessage()); e.printStackTrace(); LogUtil.d(AsyncHttpPost.class.getName(), "AsyncHttpPost request to url :" + url + " IOException " + e.getMessage()); } finally { if (!Constants.IS_STOP_REQUEST) { Message msg = new Message(); msg.obj = ret; LogUtil.d("", ret); msg.getData().putSerializable("callback", callBack); resultHandler.sendMessage(msg); } // if (customLoadingDialog != null && customLoadingDialog.isShowing()) { customLoadingDialog.dismiss(); customLoadingDialog = null; } } super.run(); }
From source file:de.escidoc.core.test.sb.SearchTestBase.java
/** * Wait until the given id exists in the given index. * //from w w w. j a v a2s .co m * @param id * resource id * @param indexName * name of the index * @param checkExists * true for existence check, false for nonexistence * @param maxTimeToWait * maximum time to wait in milliseconds * @throws Exception * Thrown if the connection to the indexer failed. */ private void waitForIndexer(final String id, final String indexName, final boolean checkExists, final long maxTimeToWait) throws Exception { long time = System.currentTimeMillis(); String query = "PID=" + id + " or distinction.rootPid=" + id; String httpUrl = getFrameworkUrl() + de.escidoc.core.test.common.client.servlet.Constants.SEARCH_BASE_URI + "/" + indexName + "?query=" + URLEncoder.encode(query, DEFAULT_CHARSET); for (;;) { HttpResponse httpRes = HttpHelper.executeHttpRequest( de.escidoc.core.test.common.client.servlet.Constants.HTTP_METHOD_GET, httpUrl, null, null, null); if (httpRes.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) { Pattern numberOfRecordsPattern = Pattern.compile("numberOfRecords>(.*?)<"); Matcher m = numberOfRecordsPattern.matcher(EntityUtils.toString(httpRes.getEntity(), HTTP.UTF_8)); if (m.find()) { if (checkExists && (Integer.parseInt(m.group(1)) > 0)) { break; } else if (!checkExists && (Integer.parseInt(m.group(1)) == 0)) { break; } } } if ((System.currentTimeMillis() - time) > maxTimeToWait) { break; } } }
From source file:com.googlecode.awsms.senders.vodafone.VodafoneWebSender.java
/** * Login to www.vodafone.it website//from w ww . jav a 2 s . co m * * @throws Exception */ private void doLogin() throws Exception { Log.d(TAG, "this.doLogin()"); try { HttpPost request = new HttpPost("https://www.vodafone.it/190/trilogy/jsp/login.do"); List<NameValuePair> requestData = new ArrayList<NameValuePair>(); requestData.add(new BasicNameValuePair("username", helper.getUsername())); requestData.add(new BasicNameValuePair("password", helper.getPassword())); request.setEntity(new UrlEncodedFormEntity(requestData, HTTP.UTF_8)); HttpResponse response = httpClient.execute(request, httpContext); response.getEntity().consumeContent(); } catch (Exception e) { throw new Exception(context.getString(R.string.WebSenderNetworkError)); } if (!isLoggedIn()) { throw new Exception(context.getString(R.string.WebSenderSettingsInvalid)); } saveCookies(); // to cookie file }
From source file:ro.zg.netcell.datasources.executors.http.HttpCommandExecutor.java
public HttpCommandResponse executeCommand(CommandContext commandContext) throws Exception { HttpClient httpClient = (HttpClient) commandContext.getConnectionManager().getConnection(); ScriptDaoCommand command = commandContext.getCommand(); String method = (String) command.getArgument("method"); String url = (String) command.getArgument("url"); /* encode the url passed on the http request */ // URI requestUri = new URI(url); // requestUri = URIUtils.createURI(requestUri.getScheme(), requestUri.getHost(), requestUri.getPort(), // requestUri.getPath(), URLEncoder.encode(requestUri.getQuery(),HTTP.DEFAULT_PROTOCOL_CHARSET), // requestUri.getFragment()); String encodedUrl = URLEncoder.encode(url, HTTP.DEFAULT_PROTOCOL_CHARSET); boolean returnHeaders = false; Object rh = command.getArgument("returnHeaders"); if (rh != null) { returnHeaders = (Boolean) rh; }/*from ww w.j ava2 s . co m*/ HttpRequestBase request = null; if ("GET".equals(method)) { request = new HttpGet(encodedUrl); } else if ("POST".equals(method)) { HttpPost post = new HttpPost(encodedUrl); String content = (String) command.getArgument("content"); if (content != null) { post.setEntity(new StringEntity(content)); } request = post; } else if ("HEAD".equals(method)) { request = new HttpHead(encodedUrl); } Map<String, String> requestHeaders = (Map) command.getArgument("requestHeaders"); if (requestHeaders != null) { for (Map.Entry<String, String> entry : requestHeaders.entrySet()) { request.setHeader(entry.getKey(), entry.getValue()); } } HttpContext localContext = new BasicHttpContext(); HttpEntity responseEntity = null; HttpCommandResponse commandResponse = new HttpCommandResponse(); try { HttpResponse response = httpClient.execute(request, localContext); responseEntity = response.getEntity(); StatusLine statusLine = response.getStatusLine(); commandResponse.setStatusCode(statusLine.getStatusCode()); commandResponse.setProtocol(statusLine.getProtocolVersion().getProtocol()); commandResponse.setReasonPhrase(statusLine.getReasonPhrase()); commandResponse.setRequestUrl(url); HttpRequest actualRequest = (HttpRequest) localContext.getAttribute(ExecutionContext.HTTP_REQUEST); HttpHost targetHost = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST); commandResponse.setTargetUrl(targetHost.toURI() + actualRequest.getRequestLine().getUri()); if (returnHeaders) { Map<String, String> headers = new HashMap<String, String>(); for (Header h : response.getAllHeaders()) { headers.put(h.getName().toLowerCase(), h.getValue().toLowerCase()); } commandResponse.setHeaders(headers); } if (responseEntity != null) { long responseLength = responseEntity.getContentLength(); String responseContent = EntityUtils.toString(responseEntity, HTTP.UTF_8); if (responseLength == -1) { responseLength = responseContent.length(); } commandResponse.setLength(responseLength); commandResponse.setContent(responseContent); } } finally { if (responseEntity != null) { responseEntity.consumeContent(); } else { request.abort(); } } return commandResponse; }
From source file:com.mediaportal.ampdroid.api.JsonClient.java
private String DoExecute(String methodName, int _timeout, RequestMethod methodType, NameValuePair... _params) throws Exception { switch (methodType) { case GET: {//from www . j a v a2s . c om // add parameters String combinedParams = ""; if (_params.length > 0) { combinedParams += "?"; for (NameValuePair p : _params) { String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(), "UTF-8"); if (combinedParams.length() > 1) { combinedParams += "&" + paramString; } else { combinedParams += paramString; } } } HttpGet request = new HttpGet(url + "/" + methodName + combinedParams); // add headers for (NameValuePair h : headers) { request.addHeader(h.getName(), h.getValue()); } return executeRequest(request, _timeout, url); } case POST: { HttpPost request = new HttpPost(url + "/" + methodName); // add headers for (NameValuePair h : headers) { request.addHeader(h.getName(), h.getValue()); } if (_params.length > 0) { List<NameValuePair> paramList = new ArrayList<NameValuePair>(); for (NameValuePair p : _params) { paramList.add(p); } request.setEntity(new UrlEncodedFormEntity(paramList, HTTP.UTF_8)); } return executeRequest(request, _timeout, url); } default: return null; } }
From source file:com.android.idtt.http.client.util.URIBuilder.java
private String encodeQuery(final List<NameValuePair> params) { return URLEncodedUtils.format(params, Charset.forName(HTTP.UTF_8)); }
From source file:com.fanfou.app.opensource.util.NetworkHelper.java
private static String encode(final String input) { try {/*from w ww. j av a2s . co m*/ return URLEncoder.encode(input, HTTP.UTF_8); } catch (final UnsupportedEncodingException e) { } return input; }
From source file:com.kkbox.toolkit.internal.api.APIRequest.java
public void addStringPostParam(String data) { try {/*from ww w .ja v a 2s.co m*/ stringEntity = new StringEntity(data, HTTP.UTF_8); } catch (Exception e) { } ; }
From source file:com.xorcode.andtweet.net.ConnectionBasicAuth.java
@Override public JSONObject updateStatus(String message, long inReplyToId) throws ConnectionException { String url = STATUSES_UPDATE_URL; List<NameValuePair> formParams = new ArrayList<NameValuePair>(); formParams.add(new BasicNameValuePair("status", message)); // This parameter was removed from API: // formParams.add(new BasicNameValuePair("source", SOURCE_PARAMETER)); if (inReplyToId > 0) { formParams.add(new BasicNameValuePair("in_reply_to_status_id", String.valueOf(inReplyToId))); }//from w w w . j a v a2s . c o m JSONObject jObj = null; try { jObj = new JSONObject(postRequest(url, new UrlEncodedFormEntity(formParams, HTTP.UTF_8))); String error = jObj.optString("error"); if ("Could not authenticate you.".equals(error)) { throw new ConnectionException(error); } } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString()); } catch (JSONException e) { throw new ConnectionException(e); } return jObj; }
From source file:org.freaknet.gtrends.api.GoogleAuthenticator.java
/** * Login in Google./* w ww.ja v a 2 s . c om*/ * * @param galx The GALX id * @return <code>true</code> if login was successful * @throws GoogleAuthenticatorException */ private boolean login(String galx) throws GoogleAuthenticatorException { _isLoggedIn = false; try { DataConfiguration config = GoogleConfigurator.getConfiguration(); HttpPost httpPost = new HttpPost(config.getString("google.auth.loginAuthenticate")); GoogleUtils.setupHttpRequestDefaults(httpPost); httpPost.setEntity(new UrlEncodedFormEntity(setupFormInputs(config, galx), HTTP.UTF_8)); HttpResponse response = _httpClient.execute(httpPost); GoogleUtils.toString(response.getEntity().getContent()); httpPost.releaseConnection(); } catch (UnsupportedEncodingException ex) { throw new GoogleAuthenticatorException(ex); } catch (ClientProtocolException ex) { throw new GoogleAuthenticatorException(ex); } catch (IOException ex) { throw new GoogleAuthenticatorException(ex); } catch (ConfigurationException ex) { throw new GoogleAuthenticatorException(ex); } _isLoggedIn = true; return _isLoggedIn; }