List of usage examples for org.apache.http.params HttpProtocolParams setContentCharset
public static void setContentCharset(HttpParams httpParams, String str)
From source file:com.gs.tools.doc.extractor.core.util.HttpUtility.java
public static DefaultHttpClient getLoginHttpsClient(String userName, String password) { try {// w w w .j a va 2s .c o m KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory sf = new DefaultSecureSocketFactory(trustStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); HttpConnectionParams.setConnectionTimeout(params, 300000); HttpConnectionParams.setSocketBufferSize(params, 10485760); HttpConnectionParams.setSoTimeout(params, 300000); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", sf, 443)); ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); DefaultHttpClient httpClient = new DefaultHttpClient(ccm, params); httpClient.getCredentialsProvider().setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM), new UsernamePasswordCredentials(userName, password)); return httpClient; } catch (Exception e) { e.printStackTrace(); return new DefaultHttpClient(); } }
From source file:com.dongfang.dicos.sina.UtilSina.java
public static HttpClient getNewHttpClient(Context context) { try {//from w w w .ja v a2 s . c o m KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory sf = new MySSLSocketFactory(trustStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 10000); HttpConnectionParams.setSoTimeout(params, 10000); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", sf, 443)); ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); // Set the default socket timeout (SO_TIMEOUT) // in // milliseconds which is the timeout for waiting for data. HttpConnectionParams.setConnectionTimeout(params, UtilSina.SET_CONNECTION_TIMEOUT); HttpConnectionParams.setSoTimeout(params, UtilSina.SET_SOCKET_TIMEOUT); HttpClient client = new DefaultHttpClient(ccm, params); WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); if (!wifiManager.isWifiEnabled()) { // ??APN Uri uri = Uri.parse("content://telephony/carriers/preferapn"); Cursor mCursor = context.getContentResolver().query(uri, null, null, null, null); if (mCursor != null && mCursor.moveToFirst()) { // ??? String proxyStr = mCursor.getString(mCursor.getColumnIndex("proxy")); if (proxyStr != null && proxyStr.trim().length() > 0) { HttpHost proxy = new HttpHost(proxyStr, 80); client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy); } mCursor.close(); } } return client; } catch (Exception e) { return new DefaultHttpClient(); } }
From source file:com.mobilyzer.Checkin.java
/** * Return an appropriately-configured HTTP client. *//*from w w w . j a v a2 s. c o m*/ private HttpClient getNewHttpClient() { DefaultHttpClient client; try { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory sf = new MySSLSocketFactory(trustStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); HttpConnectionParams.setConnectionTimeout(params, POST_TIMEOUT_MILLISEC); HttpConnectionParams.setSoTimeout(params, POST_TIMEOUT_MILLISEC); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", sf, 443)); ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); client = new DefaultHttpClient(ccm, params); } catch (Exception e) { Logger.w("Unable to create SSL HTTP client", e); client = new DefaultHttpClient(); } // TODO(mdw): For some reason this is not sending the cookie to the // test server, probably because the cookie itself is not properly // initialized. Below I manually set the Cookie header instead. CookieStore store = new BasicCookieStore(); store.addCookie(authCookie); client.setCookieStore(store); return client; }
From source file:org.dasein.cloud.atmos.AtmosMethod.java
protected @Nonnull HttpClient getClient(String endpoint) throws CloudException, InternalException { ProviderContext ctx = provider.getContext(); if (ctx == null) { throw new CloudException("No context was specified for this request"); }/*from www. j av a2s .c o m*/ boolean ssl = endpoint.startsWith("https"); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); HttpProtocolParams.setUserAgent(params, "Dasein Cloud"); Properties p = ctx.getCustomProperties(); if (p != null) { String proxyHost = p.getProperty("proxyHost"); String proxyPort = p.getProperty("proxyPort"); if (proxyHost != null) { int port = 0; if (proxyPort != null && proxyPort.length() > 0) { port = Integer.parseInt(proxyPort); } params.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, port, ssl ? "https" : "http")); } } return new DefaultHttpClient(params); }
From source file:com.mnxfst.testing.activities.http.AbstractHTTPRequestActivity.java
/** * @see com.mnxfst.testing.activities.TSPlanActivity#initialize(com.mnxfst.testing.plan.config.TSPlanConfigOption) *//*from ww w . j a v a2 s. com*/ public void initialize(TSPlanConfigOption cfg) throws TSPlanActivityExecutionException { if (cfg == null) throw new TSPlanActivityExecutionException("Failed to initialize activity '" + this.getClass().getName() + "' due to missing configuration options"); ///////////////////////////////////////////////////////////////////////////////////////// // fetch scheme, host, port and path this.scheme = (String) cfg.getOption(CFG_OPT_SCHEME); if (this.scheme == null || this.scheme.isEmpty()) throw new TSPlanActivityExecutionException( "Required config option '" + CFG_OPT_SCHEME + "' missing for activity '" + getName() + "'"); this.host = (String) cfg.getOption(CFG_OPT_HOST); if (this.host == null || this.host.isEmpty()) throw new TSPlanActivityExecutionException( "Requied config option '" + CFG_OPT_HOST + "' missing for activity '" + getName() + "'"); String portStr = (String) cfg.getOption(CFG_OPT_PORT); if (portStr != null && !portStr.isEmpty()) { try { this.port = Integer.parseInt(portStr.trim()); } catch (NumberFormatException e) { throw new TSPlanActivityExecutionException( "Failed to parse expected numerical value for config option '" + CFG_OPT_PORT + "' for activity '" + getName() + "'"); } } // fetch username and password this.basicAuthUsername = (String) cfg.getOption(CFG_OPT_BASIC_AUTH_USERNAME); this.basicAuthPassword = (String) cfg.getOption(CFG_OPT_BASIC_AUTH_PASSWORD); this.basicAuthHostScope = (String) cfg.getOption(CFG_OPT_BASIC_AUTH_HOST_SCOPE); String authPortScopeStr = (String) cfg.getOption(CFG_OPT_BASIC_AUTH_PORT_SCOPE); if (authPortScopeStr != null && !authPortScopeStr.trim().isEmpty()) { try { this.basicAuthPortScope = Integer.parseInt(authPortScopeStr.trim()); } catch (NumberFormatException e) { throw new TSPlanActivityExecutionException( "Failed to parse expected numerical value for config option '" + CFG_OPT_BASIC_AUTH_PORT_SCOPE + "' for activity '" + getName() + "'"); } } if (this.port <= 0) this.port = 80; this.path = (String) cfg.getOption(CFG_OPT_PATH); if (this.path == null || this.path.isEmpty()) this.path = "/"; String maxConnStr = (String) cfg.getOption(CFG_OPT_MAX_CONNECTIONS); if (maxConnStr != null && !maxConnStr.isEmpty()) { try { this.maxConnections = Integer.parseInt(maxConnStr); } catch (NumberFormatException e) { throw new TSPlanActivityExecutionException( "Failed to parse expected numerical value for config option '" + CFG_OPT_MAX_CONNECTIONS + "' for activity '" + getName() + "'"); } } // initialize http host and context this.httpHost = new HttpHost(this.host, this.port); // URI builder try { // query parameters List<NameValuePair> qParams = new ArrayList<NameValuePair>(); for (String key : cfg.getOptions().keySet()) { if (key.startsWith(REQUEST_PARAM_OPTION_PREFIX)) { String value = (String) cfg.getOption(key); String requestParameterName = key.substring(REQUEST_PARAM_OPTION_PREFIX.length(), key.length()); qParams.add(new BasicNameValuePair(requestParameterName, value)); if (logger.isDebugEnabled()) logger.debug("activity[name=" + getName() + ", id=" + getId() + ", requestParameter=" + requestParameterName + ", value=" + value + "]"); } } this.destinationURI = URIUtils.createURI(this.scheme, this.host, this.port, this.path, URLEncodedUtils.format(qParams, this.contentChartset), null); // TODO handle post values } catch (URISyntaxException e) { throw new TSPlanActivityExecutionException("Failed to initialize uri for [scheme=" + this.scheme + ", host=" + this.host + ", port=" + this.port + ", path=" + this.path + "]"); } httpRequestContext.setAttribute(ExecutionContext.HTTP_CONNECTION, clientConnection); httpRequestContext.setAttribute(ExecutionContext.HTTP_TARGET_HOST, httpHost); if (logger.isDebugEnabled()) logger.debug("activity[name=" + getName() + ", id=" + getId() + ", maxConnections=" + maxConnections + ", scheme=" + scheme + ", host=" + host + ", port=" + port + ", path=" + path + "]"); ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// // protocol settings this.userAgent = (String) cfg.getOption(CFG_OPT_USER_AGENT); if (this.userAgent == null || this.userAgent.isEmpty()) this.userAgent = "ptest-server"; String protocolVersion = (String) cfg.getOption(CFG_OPT_HTTP_PROTOCOL_VERSION); if (protocolVersion != null && !protocolVersion.isEmpty()) { if (protocolVersion.equalsIgnoreCase("0.9")) this.httpVersion = HttpVersion.HTTP_0_9; else if (protocolVersion.equalsIgnoreCase("1.0")) this.httpVersion = HttpVersion.HTTP_1_0; else if (protocolVersion.equalsIgnoreCase("1.1")) this.httpVersion = HttpVersion.HTTP_1_1; else throw new TSPlanActivityExecutionException("Failed to parse http protocol version '" + protocolVersion + "'. Valid value: 0.9, 1.0 and 1.1"); } this.contentChartset = (String) cfg.getOption(CFG_OPT_CONTENT_CHARSET); if (this.contentChartset == null || this.contentChartset.isEmpty()) this.contentChartset = "UTF-8"; String expectContStr = (String) cfg.getOption(CFG_OPT_EXPECT_CONTINUE); if (expectContStr != null && !expectContStr.isEmpty()) { this.expectContinue = Boolean.parseBoolean(expectContStr.trim()); } HttpProtocolParams.setUserAgent(httpParameters, userAgent); HttpProtocolParams.setVersion(httpParameters, httpVersion); HttpProtocolParams.setContentCharset(httpParameters, contentChartset); HttpProtocolParams.setUseExpectContinue(httpParameters, expectContinue); String httpProcStr = (String) cfg.getOption(CFG_OPT_HTTP_REQUEST_PROCESSORS); if (httpProcStr != null && !httpProcStr.isEmpty()) { List<HttpRequestInterceptor> interceptors = new ArrayList<HttpRequestInterceptor>(); String[] procClasses = httpProcStr.split(","); if (procClasses != null && procClasses.length > 0) { for (int i = 0; i < procClasses.length; i++) { try { Class<?> clazz = Class.forName(procClasses[i]); interceptors.add((HttpRequestInterceptor) clazz.newInstance()); if (logger.isDebugEnabled()) logger.debug("activity[name=" + getName() + ", id=" + getId() + ", httpRequestInterceptor=" + procClasses[i] + "]"); } catch (Exception e) { throw new TSPlanActivityExecutionException("Failed to instantiate http interceptor '" + procClasses[i] + "' for activity '" + getName() + "'. Error: " + e.getMessage()); } } } this.httpRequestResponseProcessor = new ImmutableHttpProcessor( (HttpRequestInterceptor[]) interceptors.toArray(EMPTY_HTTP_REQUEST_INTERCEPTOR_ARRAY)); this.hasRequestResponseProcessors = true; } this.method = (String) cfg.getOption(CFG_OPT_METHOD); if (method == null || method.isEmpty()) this.method = "GET"; if (!method.equalsIgnoreCase("get") && !method.equalsIgnoreCase("post")) throw new TSPlanActivityExecutionException( "Invalid method '" + method + "' found for activity '" + getName() + "'"); if (logger.isDebugEnabled()) logger.debug("activity[name=" + getName() + ", id=" + getId() + ", method=" + method + ", user-agent=" + userAgent + ", httpVersion=" + httpVersion + ", contentCharset=" + contentChartset + ", expectContinue=" + expectContinue + "]"); ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// // fetch proxy settings this.proxyUrl = (String) cfg.getOption(CFG_OPT_PROXY_URL); String proxyPortStr = (String) cfg.getOption(CFG_OPT_PROXY_PORT); if (proxyPortStr != null && !proxyPortStr.isEmpty()) { try { this.proxyPort = Integer.parseInt(proxyPortStr.trim()); } catch (NumberFormatException e) { throw new TSPlanActivityExecutionException( "Failed to parse expected numerical value for config option '" + CFG_OPT_PROXY_PORT + "' for activity '" + getName() + "'"); } } this.proxyUser = (String) cfg.getOption(CFG_OPT_PROXY_USER); this.proxyPassword = (String) cfg.getOption(CFG_OPT_PROXY_PASSWORD); if (proxyUrl != null && !proxyUrl.isEmpty()) { if (proxyPort > 0) this.proxyHost = new HttpHost(proxyUrl, proxyPort); else this.proxyHost = new HttpHost(proxyUrl); } if (logger.isDebugEnabled()) logger.debug("activity[name=" + getName() + ", id=" + getId() + ", proxyUrl=" + proxyUrl + ", proxyPort=" + proxyPort + ", proxyUser=" + proxyUser + "]"); ///////////////////////////////////////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////////////////////////// // // fetch request parameters // // // unfortunately we must step through the whole set of keys ... // for(String key : cfg.getOptions().keySet()) { // if(key.startsWith(REQUEST_PARAM_OPTION_PREFIX)) { // String value = (String)cfg.getOption(key); // String requestParameterName = key.substring(REQUEST_PARAM_OPTION_PREFIX.length(), key.length()); // httpParameters.setParameter(requestParameterName, value); // if(logger.isDebugEnabled()) // logger.debug("activity[name="+getName()+", id="+getId()+", requestParameter="+requestParameterName+", value="+value+"]"); // } // } // // ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// // configure scheme registry and initialize http client SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory())); if (logger.isDebugEnabled()) logger.debug("activity[name=" + getName() + ", id=" + getId() + ", registeredSchemes={http, https}]"); ThreadSafeClientConnManager threadSafeClientConnectionManager = new ThreadSafeClientConnManager( schemeRegistry); threadSafeClientConnectionManager.setMaxTotal(maxConnections); threadSafeClientConnectionManager.setDefaultMaxPerRoute(maxConnections); this.httpClient = new DefaultHttpClient(threadSafeClientConnectionManager); if (this.basicAuthUsername != null && !this.basicAuthUsername.trim().isEmpty() && this.basicAuthPassword != null && !this.basicAuthPassword.trim().isEmpty()) { UsernamePasswordCredentials creds = new UsernamePasswordCredentials(this.basicAuthUsername, this.basicAuthPassword); AuthScope authScope = null; if (basicAuthHostScope != null && !basicAuthHostScope.isEmpty() && basicAuthPortScope > 0) { authScope = new AuthScope(basicAuthHostScope, basicAuthPortScope); } else { authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT); } this.httpClient.getCredentialsProvider().setCredentials(authScope, creds); if (logger.isDebugEnabled()) logger.debug("activity[name=" + getName() + ", id=" + getId() + ", credentials=(" + creds.getUserName() + ", " + creds.getPassword() + "), authScope=(" + authScope.getHost() + ":" + authScope.getPort() + ")]"); } if (logger.isDebugEnabled()) logger.debug("activity[name=" + getName() + ", id=" + getId() + ", threadSafeClientConnectionManager=initialized]"); }
From source file:de.wikilab.android.friendica01.TwAjax.java
public DefaultHttpClient getNewHttpClient() { if (ignoreSSLCerts) { try {/*from www .ja v a2s. co m*/ KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory sf = new IgnoreCertsSSLSocketFactory(trustStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", sf, 443)); ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); return new DefaultHttpClient(ccm, params); } catch (Exception e) { return new DefaultHttpClient(); } } else { return new DefaultHttpClient(); } }
From source file:org.openmeetings.app.sip.xmlrpc.OpenXGHttpClient.java
public OpenXGReturnObject openSIPgPost(String stringToPost) { try {/* w ww . jav a2s.c o m*/ Configuration openxg_wrapper_url = cfgManagement.getConfKey(3L, "openxg.wrapper.url"); if (openxg_wrapper_url == null) { throw new Exception("No openxg.wrapper.url set in Configuration"); } String strURL = openxg_wrapper_url.getConf_value(); // Prepare HTTP post HttpPost post = new HttpPost(strURL); post.addHeader("User-Agent", "OpenSIPg XML_RPC Client"); // log.debug(stringToPost); AbstractHttpEntity entity = new ByteArrayEntity(stringToPost.getBytes(Charset.forName("ISO-8859-1"))); // Prepare HTTP post HttpParams params = post.getParams(); HttpProtocolParams.setContentCharset(params, "utf-8"); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); post.setParams(params); // Request content will be retrieved directly // from the input stream post.setEntity(entity); // Get HTTP client HttpClient httpclient = getHttpClient(); // Execute request HttpResponse response = httpclient.execute(post); int resCode = response.getStatusLine().getStatusCode(); // Display status code log.debug("Response status code: " + response); if (resCode == 200) { HttpEntity ent = response.getEntity(); String responseBody = (ent != null) ? EntityUtils.toString(ent) : ""; log.debug("parseReturnBody " + responseBody); OpenXGReturnObject oIG = this.parseOpenXGReturnBody(ent.getContent()); log.debug("oIG 1 " + oIG.getStatus_code()); log.debug("oIG 2 " + oIG.getStatus_string()); return oIG; } else { throw new Exception("Could not connect to OpenXG, check the URL for the Configuration"); } } catch (Exception err) { log.error("[openSIPgUserCreate]", err); } return null; }
From source file:org.dasein.cloud.azure.AzureMethod.java
protected @Nonnull HttpClient getClient() throws CloudException, InternalException { ProviderContext ctx = provider.getContext(); if (ctx == null) { throw new AzureConfigException("No context was defined for this request"); }//from w ww. j av a2 s . com String endpoint = ctx.getEndpoint(); if (endpoint == null) { throw new AzureConfigException("No cloud endpoint was defined"); } boolean ssl = endpoint.startsWith("https"); int targetPort; try { URI uri = new URI(endpoint); targetPort = uri.getPort(); if (targetPort < 1) { targetPort = (ssl ? 443 : 80); } } catch (URISyntaxException e) { throw new AzureConfigException(e); } HttpParams params = new BasicHttpParams(); SchemeRegistry registry = new SchemeRegistry(); try { registry.register( new Scheme(ssl ? "https" : "http", targetPort, new AzureSSLSocketFactory(new AzureX509(ctx)))); } catch (KeyManagementException e) { e.printStackTrace(); throw new InternalException(e); } catch (UnrecoverableKeyException e) { e.printStackTrace(); throw new InternalException(e); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new InternalException(e); } catch (KeyStoreException e) { e.printStackTrace(); throw new InternalException(e); } HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); HttpProtocolParams.setUserAgent(params, "Dasein Cloud"); params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000); params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 300000); Properties p = ctx.getCustomProperties(); if (p != null) { String proxyHost = p.getProperty("proxyHost"); String proxyPort = p.getProperty("proxyPort"); if (proxyHost != null) { int port = 0; if (proxyPort != null && proxyPort.length() > 0) { port = Integer.parseInt(proxyPort); } params.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, port, ssl ? "https" : "http")); } } ClientConnectionManager ccm = new ThreadSafeClientConnManager(registry); return new DefaultHttpClient(ccm, params); }
From source file:com.cloverstudio.spika.couchdb.ConnectionHandler.java
public static String getIdFromFileUploader(String url, List<NameValuePair> params) throws ClientProtocolException, IOException, UnsupportedOperationException, SpikaException, JSONException {/* www. j a v a 2 s.c o m*/ // Making HTTP request // defaultHttpClient HttpParams httpParams = new BasicHttpParams(); HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(httpParams, "UTF-8"); HttpClient httpClient = new DefaultHttpClient(httpParams); HttpPost httpPost = new HttpPost(url); httpPost.setHeader("database", Const.DATABASE); Charset charSet = Charset.forName("UTF-8"); // Setting up the // encoding MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); for (int index = 0; index < params.size(); index++) { if (params.get(index).getName().equalsIgnoreCase(Const.FILE)) { // If the key equals to "file", we use FileBody to // transfer the data entity.addPart(params.get(index).getName(), new FileBody(new File(params.get(index).getValue()))); } else { // Normal string data entity.addPart(params.get(index).getName(), new StringBody(params.get(index).getValue(), charSet)); } } httpPost.setEntity(entity); print(httpPost); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); InputStream is = httpEntity.getContent(); // if (httpResponse.getStatusLine().getStatusCode() > 400) // { // if (httpResponse.getStatusLine().getStatusCode() == 500) throw new SpikaException(ConnectionHandler.getError(entity.getContent())); // throw new IOException(httpResponse.getStatusLine().getReasonPhrase()); // } // BufferedReader reader = new BufferedReader(new // InputStreamReader(is, "iso-8859-1"), 8); BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line); } is.close(); String json = sb.toString(); Logger.debug("RESPONSE", json); return json; }
From source file:com.android.callstat.common.net.ConnectionThread.java
private static MyHttpClient createHttpClient(Context context) { String userAgent = CallStatApplication.DEFAULT_USER_AGENT; MyHttpClient client = MyHttpClient.newInstance(userAgent, context); HttpParams params = client.getParams(); HttpProtocolParams.setContentCharset(params, "UTF-8"); // HttpClientParams.setRedirecting(params, true); // set the socket timeout int soTimeout = CallStatApplication.HTTP_SOCKET_TIMEOUT; if (DebugFlags.CONNECTION_THREAD) { HttpLog.v(/*w w w . j a va 2 s . c om*/ "[HttpUtils] createHttpClient w/ socket timeout " + soTimeout + " ms, " + ", UA=" + userAgent); } HttpConnectionParams.setSoTimeout(params, soTimeout); return client; }