List of usage examples for java.net HttpURLConnection setReadTimeout
public void setReadTimeout(int timeout)
From source file:cgeo.geocaching.cgBase.java
public static void postTweet(cgeoapplication app, cgSettings settings, String status, final Geopoint coords) { if (app == null) { return;//from ww w . ja va 2 s . c o m } if (settings == null || StringUtils.isBlank(settings.tokenPublic) || StringUtils.isBlank(settings.tokenSecret)) { return; } try { Map<String, String> parameters = new HashMap<String, String>(); parameters.put("status", status); if (coords != null) { parameters.put("lat", String.format("%.6f", coords.getLatitude())); parameters.put("long", String.format("%.6f", coords.getLongitude())); parameters.put("display_coordinates", "true"); } final String paramsDone = cgOAuth.signOAuth("api.twitter.com", "/1/statuses/update.json", "POST", false, parameters, settings.tokenPublic, settings.tokenSecret); HttpURLConnection connection = null; try { final StringBuffer buffer = new StringBuffer(); final URL u = new URL("http://api.twitter.com/1/statuses/update.json"); final URLConnection uc = u.openConnection(); uc.setRequestProperty("Host", "api.twitter.com"); connection = (HttpURLConnection) uc; connection.setReadTimeout(30000); connection.setRequestMethod("POST"); HttpURLConnection.setFollowRedirects(true); connection.setDoInput(true); connection.setDoOutput(true); final OutputStream out = connection.getOutputStream(); final OutputStreamWriter wr = new OutputStreamWriter(out); wr.write(paramsDone); wr.flush(); wr.close(); Log.i(cgSettings.tag, "Twitter.com: " + connection.getResponseCode() + " " + connection.getResponseMessage()); InputStream ins; final String encoding = connection.getContentEncoding(); if (encoding != null && encoding.equalsIgnoreCase("gzip")) { ins = new GZIPInputStream(connection.getInputStream()); } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) { ins = new InflaterInputStream(connection.getInputStream(), new Inflater(true)); } else { ins = connection.getInputStream(); } final InputStreamReader inr = new InputStreamReader(ins); final BufferedReader br = new BufferedReader(inr); readIntoBuffer(br, buffer); br.close(); ins.close(); inr.close(); connection.disconnect(); } catch (IOException e) { Log.e(cgSettings.tag, "cgBase.postTweet.IO: " + connection.getResponseCode() + ": " + connection.getResponseMessage() + " ~ " + e.toString()); final InputStream ins = connection.getErrorStream(); final StringBuffer buffer = new StringBuffer(); final InputStreamReader inr = new InputStreamReader(ins); final BufferedReader br = new BufferedReader(inr); readIntoBuffer(br, buffer); br.close(); ins.close(); inr.close(); } catch (Exception e) { Log.e(cgSettings.tag, "cgBase.postTweet.inner: " + e.toString()); } connection.disconnect(); } catch (Exception e) { Log.e(cgSettings.tag, "cgBase.postTweet: " + e.toString()); } }
From source file:com.sckftr.android.utils.net.Network.java
/** * Call the webservice using the given parameters to construct the request and return the * result.//from www .ja v a 2 s . c om * * * @param context The context to use for this operation. Used to generate the user agent if * needed. * @param urlValue The webservice URL. * @param method The request method to use. * @param handler *@param parameterList The parameters to add to the request. * @param headerMap The headers to add to the request. * @param isGzipEnabled Whether the request will use gzip compression if available on the * server. * @param userAgent The user agent to set in the request. If null, a default Android one will be * created. * @param postText The POSTDATA text to add in the request. * @param credentials The credentials to use for authentication. * @param isSslValidationEnabled Whether the request will validate the SSL certificates. @return The result of the webservice call. */ static <Out> Out execute(Context context, String urlValue, Method method, Executor<BufferedReader, Out> handler, ArrayList<BasicNameValuePair> parameterList, HashMap<String, String> headerMap, boolean isGzipEnabled, String userAgent, String postText, UsernamePasswordCredentials credentials, boolean isSslValidationEnabled) throws NetworkConnectionException { HttpURLConnection connection = null; try { // Prepare the request information if (userAgent == null) { userAgent = UserAgentUtils.get(context); } if (headerMap == null) { headerMap = new HashMap<String, String>(); } headerMap.put(HTTP.USER_AGENT, userAgent); if (isGzipEnabled) { headerMap.put(ACCEPT_ENCODING_HEADER, "gzip"); } headerMap.put(ACCEPT_CHARSET_HEADER, UTF8_CHARSET); if (credentials != null) { headerMap.put(AUTHORIZATION_HEADER, createAuthenticationHeader(credentials)); } StringBuilder paramBuilder = new StringBuilder(); if (parameterList != null && !parameterList.isEmpty()) { for (int i = 0, size = parameterList.size(); i < size; i++) { BasicNameValuePair parameter = parameterList.get(i); String name = parameter.getName(); String value = parameter.getValue(); if (TextUtils.isEmpty(name)) { // Empty parameter name. Check the next one. continue; } if (value == null) { value = ""; } paramBuilder.append(URLEncoder.encode(name, UTF8_CHARSET)); paramBuilder.append("="); paramBuilder.append(URLEncoder.encode(value, UTF8_CHARSET)); paramBuilder.append("&"); } } // Log the request //if (Log.canLog(Log.DEBUG)) { Log.d(TAG, method.toString() + ": " + urlValue); if (parameterList != null && !parameterList.isEmpty()) { //Log.d(TAG, "Parameters:"); for (int i = 0, size = parameterList.size(); i < size; i++) { BasicNameValuePair parameter = parameterList.get(i); String message = "- \"" + parameter.getName() + "\" = \"" + parameter.getValue() + "\""; Log.d(TAG, message); } //Log.d(TAG, "Parameters String: \"" + paramBuilder.toString() + "\""); } if (postText != null) { Log.d(TAG, "Post data: " + postText); } if (headerMap != null && !headerMap.isEmpty()) { //Log.d(TAG, "Headers:"); for (Entry<String, String> header : headerMap.entrySet()) { //Log.d(TAG, "- " + header.getKey() + " = " + header.getValue()); } } //} // Create the connection object URL url = null; String outputText = null; switch (method) { case GET: case DELETE: String fullUrlValue = urlValue; if (paramBuilder.length() > 0) { fullUrlValue += "?" + paramBuilder.toString(); } url = new URL(fullUrlValue); connection = (HttpURLConnection) url.openConnection(); break; case PUT: case POST: url = new URL(urlValue); connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); if (paramBuilder.length() > 0) { outputText = paramBuilder.toString(); headerMap.put(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded"); headerMap.put(HTTP.CONTENT_LEN, String.valueOf(outputText.getBytes().length)); } else if (postText != null) { outputText = postText; } break; } // Set the request method connection.setRequestMethod(method.toString()); // If it's an HTTPS request and the SSL Validation is disabled if (url.getProtocol().equals("https") && !isSslValidationEnabled) { HttpsURLConnection httpsConnection = (HttpsURLConnection) connection; httpsConnection.setSSLSocketFactory(getAllHostsValidSocketFactory()); httpsConnection.setHostnameVerifier(getAllHostsValidVerifier()); } // Add the headers if (!headerMap.isEmpty()) { for (Entry<String, String> header : headerMap.entrySet()) { connection.addRequestProperty(header.getKey(), header.getValue()); } } // Set the connection and read timeout connection.setConnectTimeout(OPERATION_TIMEOUT); connection.setReadTimeout(OPERATION_TIMEOUT); // Set the outputStream content for POST and PUT requests if ((method == Method.POST || method == Method.PUT) && outputText != null) { OutputStream output = null; try { output = connection.getOutputStream(); output.write(outputText.getBytes()); } finally { if (output != null) { try { output.close(); } catch (IOException e) { // Already catching the first IOException so nothing to do here. } } } } String contentEncoding = connection.getHeaderField(HTTP.CONTENT_ENCODING); int responseCode = connection.getResponseCode(); boolean isGzip = contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip"); Log.d(TAG, "Response code: " + responseCode); if (responseCode == HttpStatus.SC_MOVED_PERMANENTLY) { String redirectionUrl = connection.getHeaderField(LOCATION_HEADER); throw new NetworkConnectionException("New location : " + redirectionUrl, redirectionUrl); } InputStream errorStream = connection.getErrorStream(); if (errorStream != null) { String err = evaluateStream(errorStream, new StringReaderHandler(), isGzip); throw new NetworkConnectionException(err, responseCode); } return evaluateStream(connection.getInputStream(), handler, isGzip); } catch (IOException e) { Log.e(TAG, "IOException", e); throw new NetworkConnectionException(e); } catch (KeyManagementException e) { Log.e(TAG, "KeyManagementException", e); throw new NetworkConnectionException(e); } catch (NoSuchAlgorithmException e) { Log.e(TAG, "NoSuchAlgorithmException", e); throw new NetworkConnectionException(e); } finally { if (connection != null) { connection.disconnect(); } } }
From source file:com.phicomm.account.network.NetworkConnectionImpl.java
/** * Call the webservice using the given parameters to construct the request and return the * result./*from w ww.j a v a2s.c o m*/ * * @param context The context to use for this operation. Used to generate the user agent if * needed. * @param urlValue The webservice URL. * @param method The request method to use. * @param parameterList The parameters to add to the request. * @param headerMap The headers to add to the request. * @param isGzipEnabled Whether the request will use gzip compression if available on the * server. * @param userAgent The user agent to set in the request. If null, a default Android one will be * created. * @param postText The POSTDATA text to add in the request. * @param credentials The credentials to use for authentication. * @param isSslValidationEnabled Whether the request will validate the SSL certificates. * @return The result of the webservice call. */ public static ConnectionResult execute(Context context, String urlValue, Method method, ArrayList<BasicNameValuePair> parameterList, HashMap<String, String> headerMap, boolean isGzipEnabled, String userAgent, String postText, UsernamePasswordCredentials credentials, boolean isSslValidationEnabled) throws ConnectionException { Thread.dumpStack(); Log.i("ss", "NetworkConnectionImpl_____________________________________execute__urlValue:" + urlValue); HttpURLConnection connection = null; try { // Prepare the request information if (userAgent == null) { userAgent = UserAgentUtils.get(context); } if (headerMap == null) { headerMap = new HashMap<String, String>(); } headerMap.put(HTTP.USER_AGENT, userAgent); if (isGzipEnabled) { headerMap.put(ACCEPT_ENCODING_HEADER, "gzip"); } headerMap.put(ACCEPT_CHARSET_HEADER, UTF8_CHARSET); if (credentials != null) { headerMap.put(AUTHORIZATION_HEADER, createAuthenticationHeader(credentials)); } StringBuilder paramBuilder = new StringBuilder(); if (parameterList != null && !parameterList.isEmpty()) { for (int i = 0, size = parameterList.size(); i < size; i++) { BasicNameValuePair parameter = parameterList.get(i); String name = parameter.getName(); String value = parameter.getValue(); if (TextUtils.isEmpty(name)) { // Empty parameter name. Check the next one. continue; } if (value == null) { value = ""; } paramBuilder.append(URLEncoder.encode(name, UTF8_CHARSET)); paramBuilder.append("="); paramBuilder.append(URLEncoder.encode(value, UTF8_CHARSET)); paramBuilder.append("&"); } } // Log the request if (true) { Log.d(TAG, "Request url: " + urlValue); Log.d(TAG, "Method: " + method.toString()); if (parameterList != null && !parameterList.isEmpty()) { Log.d(TAG, "Parameters:"); for (int i = 0, size = parameterList.size(); i < size; i++) { BasicNameValuePair parameter = parameterList.get(i); String message = "- \"" + parameter.getName() + "\" = \"" + parameter.getValue() + "\""; Log.d(TAG, message); } Log.d(TAG, "Parameters String: \"" + paramBuilder.toString() + "\""); } if (postText != null) { Log.d(TAG, "Post data: " + postText); } if (headerMap != null && !headerMap.isEmpty()) { Log.d(TAG, "Headers:"); for (Entry<String, String> header : headerMap.entrySet()) { Log.d(TAG, "- " + header.getKey() + " = " + header.getValue()); } } } // Create the connection object URL url = null; String outputText = null; switch (method) { case GET: case DELETE: String fullUrlValue = urlValue; if (paramBuilder.length() > 0) { fullUrlValue += "?" + paramBuilder.toString(); } url = new URL(fullUrlValue); connection = HttpUrlConnectionHelper.openUrlConnection(url); break; case PUT: case POST: url = new URL(urlValue); connection = HttpUrlConnectionHelper.openUrlConnection(url); connection.setDoOutput(true); if (paramBuilder.length() > 0) { outputText = paramBuilder.toString(); headerMap.put(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded"); headerMap.put(HTTP.CONTENT_LEN, String.valueOf(outputText.getBytes().length)); } else if (postText != null) { outputText = postText; } break; } // Set the request method connection.setRequestMethod(method.toString()); // If it's an HTTPS request and the SSL Validation is disabled if (url.getProtocol().equals("https") && !isSslValidationEnabled) { HttpsURLConnection httpsConnection = (HttpsURLConnection) connection; httpsConnection.setSSLSocketFactory(getAllHostsValidSocketFactory()); httpsConnection.setHostnameVerifier(getAllHostsValidVerifier()); } // Add the headers if (!headerMap.isEmpty()) { for (Entry<String, String> header : headerMap.entrySet()) { connection.addRequestProperty(header.getKey(), header.getValue()); } } // Set the connection and read timeout connection.setConnectTimeout(OPERATION_TIMEOUT); connection.setReadTimeout(OPERATION_TIMEOUT); // Set the outputStream content for POST and PUT requests if ((method == Method.POST || method == Method.PUT) && outputText != null) { OutputStream output = null; try { output = connection.getOutputStream(); output.write(outputText.getBytes()); } finally { if (output != null) { try { output.close(); } catch (IOException e) { // Already catching the first IOException so nothing to do here. } } } } String contentEncoding = connection.getHeaderField(HTTP.CONTENT_ENCODING); int responseCode = connection.getResponseCode(); boolean isGzip = contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip"); Log.d(TAG, "Response code: " + responseCode); if (responseCode == HttpStatus.SC_MOVED_PERMANENTLY) { String redirectionUrl = connection.getHeaderField(LOCATION_HEADER); throw new ConnectionException("New location : " + redirectionUrl, redirectionUrl); } InputStream errorStream = connection.getErrorStream(); if (errorStream != null) { String error = convertStreamToString(errorStream, isGzip); throw new ConnectionException(error, responseCode); } String body = convertStreamToString(connection.getInputStream(), isGzip); if (true) { Log.v(TAG, "Response body: "); int pos = 0; int bodyLength = body.length(); while (pos < bodyLength) { Log.v(TAG, body.substring(pos, Math.min(bodyLength - 1, pos + 200))); pos = pos + 200; } } return new ConnectionResult(connection.getHeaderFields(), body); } catch (IOException e) { Log.e(TAG, "IOException", e); throw new ConnectionException(e); } catch (KeyManagementException e) { Log.e(TAG, "KeyManagementException", e); throw new ConnectionException(e); } catch (NoSuchAlgorithmException e) { Log.e(TAG, "NoSuchAlgorithmException", e); throw new ConnectionException(e); } finally { if (connection != null) { connection.disconnect(); } } }
From source file:com.foxykeep.datadroid.internal.network.NetworkConnectionImpl.java
/** * Call the webservice using the given parameters to construct the request and return the * result.//from www.j a v a 2 s . c o m * * @param context The context to use for this operation. Used to generate the user agent if * needed. * @param urlValue The webservice URL. * @param method The request method to use. * @param parameterList The parameters to add to the request. * @param headerMap The headers to add to the request. * @param isGzipEnabled Whether the request will use gzip compression if available on the * server. * @param userAgent The user agent to set in the request. If null, a default Android one will be * created. * @param postText The POSTDATA text to add in the request. * @param credentials The credentials to use for authentication. * @param isSslValidationEnabled Whether the request will validate the SSL certificates. * @return The result of the webservice call. */ public static ConnectionResult execute(Context context, String urlValue, Method method, ArrayList<BasicNameValuePair> parameterList, HashMap<String, String> headerMap, boolean isGzipEnabled, String userAgent, String postText, UsernamePasswordCredentials credentials, boolean isSslValidationEnabled) throws ConnectionException { HttpURLConnection connection = null; try { // Prepare the request information if (userAgent == null) { userAgent = UserAgentUtils.get(context); } if (headerMap == null) { headerMap = new HashMap<String, String>(); } headerMap.put(HTTP.USER_AGENT, userAgent); if (isGzipEnabled) { headerMap.put(ACCEPT_ENCODING_HEADER, "gzip"); } headerMap.put(ACCEPT_CHARSET_HEADER, UTF8_CHARSET); if (credentials != null) { headerMap.put(AUTHORIZATION_HEADER, createAuthenticationHeader(credentials)); } StringBuilder paramBuilder = new StringBuilder(); if (parameterList != null && !parameterList.isEmpty()) { for (int i = 0, size = parameterList.size(); i < size; i++) { BasicNameValuePair parameter = parameterList.get(i); String name = parameter.getName(); String value = parameter.getValue(); if (TextUtils.isEmpty(name)) { // Empty parameter name. Check the next one. continue; } if (value == null) { value = ""; } paramBuilder.append(URLEncoder.encode(name, UTF8_CHARSET)); paramBuilder.append("="); paramBuilder.append(URLEncoder.encode(value, UTF8_CHARSET)); paramBuilder.append("&"); } } // Log the request if (DataDroidLog.canLog(Log.DEBUG)) { DataDroidLog.d(TAG, "Request url: " + urlValue); DataDroidLog.d(TAG, "Method: " + method.toString()); if (parameterList != null && !parameterList.isEmpty()) { DataDroidLog.d(TAG, "Parameters:"); for (int i = 0, size = parameterList.size(); i < size; i++) { BasicNameValuePair parameter = parameterList.get(i); String message = "- \"" + parameter.getName() + "\" = \"" + parameter.getValue() + "\""; DataDroidLog.d(TAG, message); } DataDroidLog.d(TAG, "Parameters String: \"" + paramBuilder.toString() + "\""); } if (postText != null) { DataDroidLog.d(TAG, "Post data: " + postText); } if (headerMap != null && !headerMap.isEmpty()) { DataDroidLog.d(TAG, "Headers:"); for (Entry<String, String> header : headerMap.entrySet()) { DataDroidLog.d(TAG, "- " + header.getKey() + " = " + header.getValue()); } } } // Create the connection object URL url = null; String outputText = null; switch (method) { case GET: case DELETE: String fullUrlValue = urlValue; if (paramBuilder.length() > 0) { fullUrlValue += "?" + paramBuilder.toString(); } url = new URL(fullUrlValue); connection = HttpUrlConnectionHelper.openUrlConnection(url); break; case PUT: case POST: url = new URL(urlValue); connection = HttpUrlConnectionHelper.openUrlConnection(url); connection.setDoOutput(true); if (paramBuilder.length() > 0) { outputText = paramBuilder.toString(); headerMap.put(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded"); headerMap.put(HTTP.CONTENT_LEN, String.valueOf(outputText.getBytes().length)); } else if (postText != null) { outputText = postText; } break; } // Set the request method connection.setRequestMethod(method.toString()); // If it's an HTTPS request and the SSL Validation is disabled if (url.getProtocol().equals("https") && !isSslValidationEnabled) { HttpsURLConnection httpsConnection = (HttpsURLConnection) connection; httpsConnection.setSSLSocketFactory(getAllHostsValidSocketFactory()); httpsConnection.setHostnameVerifier(getAllHostsValidVerifier()); } // Add the headers if (!headerMap.isEmpty()) { for (Entry<String, String> header : headerMap.entrySet()) { connection.addRequestProperty(header.getKey(), header.getValue()); } } // Set the connection and read timeout connection.setConnectTimeout(OPERATION_TIMEOUT); connection.setReadTimeout(OPERATION_TIMEOUT); // Set the outputStream content for POST and PUT requests if ((method == Method.POST || method == Method.PUT) && outputText != null) { OutputStream output = null; try { output = connection.getOutputStream(); output.write(outputText.getBytes()); } finally { if (output != null) { try { output.close(); } catch (IOException e) { // Already catching the first IOException so nothing to do here. } } } } String contentEncoding = connection.getHeaderField(HTTP.CONTENT_ENCODING); int responseCode = connection.getResponseCode(); boolean isGzip = contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip"); DataDroidLog.d(TAG, "Response code: " + responseCode); if (responseCode == HttpStatus.SC_MOVED_PERMANENTLY) { String redirectionUrl = connection.getHeaderField(LOCATION_HEADER); throw new ConnectionException("New location : " + redirectionUrl, redirectionUrl); } InputStream errorStream = connection.getErrorStream(); if (errorStream != null) { String error = convertStreamToString(errorStream, isGzip); throw new ConnectionException(error, responseCode); } String body = convertStreamToString(connection.getInputStream(), isGzip); if (DataDroidLog.canLog(Log.VERBOSE)) { DataDroidLog.v(TAG, "Response body: "); int pos = 0; int bodyLength = body.length(); while (pos < bodyLength) { DataDroidLog.v(TAG, body.substring(pos, Math.min(bodyLength - 1, pos + 200))); pos = pos + 200; } } return new ConnectionResult(connection.getHeaderFields(), body); } catch (IOException e) { DataDroidLog.e(TAG, "IOException", e); throw new ConnectionException(e); } catch (KeyManagementException e) { DataDroidLog.e(TAG, "KeyManagementException", e); throw new ConnectionException(e); } catch (NoSuchAlgorithmException e) { DataDroidLog.e(TAG, "NoSuchAlgorithmException", e); throw new ConnectionException(e); } finally { if (connection != null) { connection.disconnect(); } } }
From source file:com.foxykeep.datadroid.internal.network.NetworkConnectionImplF.java
/** * Call the webservice using the given parameters to construct the request and return the * result./*from w ww .j a va 2 s. com*/ * * @param context The context to use for this operation. Used to generate the user agent if * needed. * @param urlValue The webservice URL. * @param method The request method to use. * @param parameterList The parameters to add to the request. * @param headerMap The headers to add to the request. * @param isGzipEnabled Whether the request will use gzip compression if available on the * server. * @param userAgent The user agent to set in the request. If null, a default Android one will be * created. * @param postText The POSTDATA text to add in the request. * @param credentials The credentials to use for authentication. * @param isSslValidationEnabled Whether the request will validate the SSL certificates. * @return The result of the webservice call. */ public static ConnectionResult execute(Context context, String urlValue, Method method, ArrayList<BasicNameValuePair> parameterList, HashMap<String, String> headerMap, boolean isGzipEnabled, String userAgent, String postText, UsernamePasswordCredentials credentials, boolean isSslValidationEnabled, File file) throws ConnectionException { HttpURLConnection connection = null; try { // Prepare the request information if (userAgent == null) { userAgent = UserAgentUtils.get(context); } if (headerMap == null) { headerMap = new HashMap<String, String>(); } headerMap.put(HTTP.USER_AGENT, userAgent); if (isGzipEnabled) { headerMap.put(ACCEPT_ENCODING_HEADER, "gzip"); } headerMap.put(ACCEPT_CHARSET_HEADER, UTF8_CHARSET); if (credentials != null) { headerMap.put(AUTHORIZATION_HEADER, createAuthenticationHeader(credentials)); } StringBuilder paramBuilder = new StringBuilder(); if (parameterList != null && !parameterList.isEmpty()) { for (int i = 0, size = parameterList.size(); i < size; i++) { BasicNameValuePair parameter = parameterList.get(i); String name = parameter.getName(); String value = parameter.getValue(); if (TextUtils.isEmpty(name)) { // Empty parameter name. Check the next one. continue; } if (value == null) { value = ""; } paramBuilder.append(URLEncoder.encode(name, UTF8_CHARSET)); paramBuilder.append("="); paramBuilder.append(URLEncoder.encode(value, UTF8_CHARSET)); paramBuilder.append("&"); } } // Log the request if (DataDroidLog.canLog(Log.DEBUG)) { DataDroidLog.d(TAG, "Request url: " + urlValue); DataDroidLog.d(TAG, "Method: " + method.toString()); if (parameterList != null && !parameterList.isEmpty()) { DataDroidLog.d(TAG, "Parameters:"); for (int i = 0, size = parameterList.size(); i < size; i++) { BasicNameValuePair parameter = parameterList.get(i); String message = "- \"" + parameter.getName() + "\" = \"" + parameter.getValue() + "\""; DataDroidLog.d(TAG, message); } DataDroidLog.d(TAG, "Parameters String: \"" + paramBuilder.toString() + "\""); } if (postText != null) { DataDroidLog.d(TAG, "Post data: " + postText); } if (headerMap != null && !headerMap.isEmpty()) { DataDroidLog.d(TAG, "Headers:"); for (Entry<String, String> header : headerMap.entrySet()) { DataDroidLog.d(TAG, "- " + header.getKey() + " = " + header.getValue()); } } } // Create the connection object URL url = null; String outputText = null; switch (method) { case GET: case DELETE: String fullUrlValue = urlValue; if (paramBuilder.length() > 0) { fullUrlValue += "?" + paramBuilder.toString(); } url = new URL(fullUrlValue); connection = (HttpURLConnection) url.openConnection(); break; case PUT: case POST: url = new URL(urlValue); connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); if (paramBuilder.length() > 0) { outputText = paramBuilder.toString(); headerMap.put(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded"); headerMap.put(HTTP.CONTENT_LEN, String.valueOf(outputText.getBytes().length)); } else if (postText != null) { outputText = postText; } break; } // Set the request method connection.setRequestMethod(method.toString()); // If it's an HTTPS request and the SSL Validation is disabled if (url.getProtocol().equals("https") && !isSslValidationEnabled) { HttpsURLConnection httpsConnection = (HttpsURLConnection) connection; httpsConnection.setSSLSocketFactory(getAllHostsValidSocketFactory()); httpsConnection.setHostnameVerifier(getAllHostsValidVerifier()); } // Add the headers if (!headerMap.isEmpty()) { for (Entry<String, String> header : headerMap.entrySet()) { connection.addRequestProperty(header.getKey(), header.getValue()); } } // Set the connection and read timeout connection.setConnectTimeout(OPERATION_TIMEOUT); connection.setReadTimeout(READ_OPERATION_TIMEOUT); // Set the outputStream content for POST and PUT requests if ((method == Method.POST || method == Method.PUT) && outputText != null) { OutputStream output = null; try { output = connection.getOutputStream(); output.write(outputText.getBytes()); } finally { if (output != null) { try { output.close(); } catch (IOException e) { // Already catching the first IOException so nothing to do here. } } } } String contentEncoding = connection.getHeaderField(HTTP.CONTENT_ENCODING); int responseCode = connection.getResponseCode(); boolean isGzip = contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip"); DataDroidLog.d(TAG, "Response code: " + responseCode); if (responseCode == HttpStatus.SC_MOVED_PERMANENTLY) { String redirectionUrl = connection.getHeaderField(LOCATION_HEADER); throw new ConnectionException("New location : " + redirectionUrl, redirectionUrl); } InputStream errorStream = connection.getErrorStream(); if (errorStream != null) { throw new ConnectionException("error", responseCode); } String body = convertStreamToString(connection.getInputStream(), isGzip, file, context); return new ConnectionResult(connection.getHeaderFields(), body); } catch (IOException e) { DataDroidLog.e(TAG, "IOException", e); throw new ConnectionException(e); } catch (KeyManagementException e) { DataDroidLog.e(TAG, "KeyManagementException", e); throw new ConnectionException(e); } catch (NoSuchAlgorithmException e) { DataDroidLog.e(TAG, "NoSuchAlgorithmException", e); throw new ConnectionException(e); } finally { if (connection != null) { connection.disconnect(); } } }
From source file:com.google.code.linkedinapi.client.impl.BaseLinkedInApiClient.java
/** * @param apiUrl//from w w w .j a v a2 s . c om * @param expected * @param httpHeaders * @return */ protected InputStream callApiMethod(String apiUrl, int expected, List<HttpHeader> httpHeaders) { try { LinkedInOAuthService oAuthService = LinkedInOAuthServiceFactory.getInstance() .createLinkedInOAuthService(apiConsumer.getConsumerKey(), apiConsumer.getConsumerSecret()); if (accessToken.getOauth2Token() != null && !accessToken.getOauth2Token().isEmpty()) { // oauth2 token hack, this seemed like the easiest... place to do it if (apiUrl.contains("?")) { apiUrl = apiUrl + "&oauth2_access_token=" + accessToken.getOauth2Token(); } else { apiUrl = apiUrl + "?oauth2_access_token=" + accessToken.getOauth2Token(); } } if (OUTPUT_RESPONSE) { LOG.info("Calling LinkedIn URL: " + apiUrl); } URL url = new URL(apiUrl); HttpURLConnection request = (HttpURLConnection) url.openConnection(); if (ApplicationConstants.CONNECT_TIMEOUT > -1) { request.setConnectTimeout(ApplicationConstants.CONNECT_TIMEOUT); } if (ApplicationConstants.READ_TIMEOUT > -1) { request.setReadTimeout(ApplicationConstants.READ_TIMEOUT); } for (String headerName : requestHeaders.keySet()) { request.setRequestProperty(headerName, requestHeaders.get(headerName)); } for (HttpHeader header : httpHeaders) { request.setRequestProperty(header.getName(), header.getValue()); } oAuthService.signRequestWithToken(request, accessToken); request.connect(); if (request.getResponseCode() != expected) { Error error = readResponse(Error.class, getWrappedInputStream(request.getErrorStream(), GZIP_ENCODING.equalsIgnoreCase(request.getContentEncoding()))); throw createLinkedInApiClientException(error); } else { return getWrappedInputStream(request.getInputStream(), GZIP_ENCODING.equalsIgnoreCase(request.getContentEncoding())); } } catch (IOException e) { throw new LinkedInApiClientException(e); } }
From source file:com.google.code.linkedinapi.client.impl.BaseLinkedInApiClient.java
/** * @param apiUrl/*from w ww .j a v a2s. co m*/ * @param xmlContent * @param contentType * @param method * @param expected * @return */ protected void callApiMethod(String apiUrl, String xmlContent, String contentType, HttpMethod method, int expected) { try { LinkedInOAuthService oAuthService = LinkedInOAuthServiceFactory.getInstance() .createLinkedInOAuthService(apiConsumer.getConsumerKey(), apiConsumer.getConsumerSecret()); if (accessToken.getOauth2Token() != null && !accessToken.getOauth2Token().isEmpty()) { // oauth2 token hack, this seemed like the easiest... place to do it if (apiUrl.contains("?")) { apiUrl = apiUrl + "&oauth2_access_token=" + accessToken.getOauth2Token(); } else { apiUrl = apiUrl + "?oauth2_access_token=" + accessToken.getOauth2Token(); } } if (OUTPUT_RESPONSE) { LOG.info("Calling LinkedIn URL: " + apiUrl); LOG.info("XML Content: " + xmlContent); } URL url = new URL(apiUrl); HttpURLConnection request = (HttpURLConnection) url.openConnection(); if (ApplicationConstants.CONNECT_TIMEOUT > -1) { request.setConnectTimeout(ApplicationConstants.CONNECT_TIMEOUT); } if (ApplicationConstants.READ_TIMEOUT > -1) { request.setReadTimeout(ApplicationConstants.READ_TIMEOUT); } for (String headerName : requestHeaders.keySet()) { request.setRequestProperty(headerName, requestHeaders.get(headerName)); } request.setRequestMethod(method.fieldName()); request.setDoOutput(true); oAuthService.signRequestWithToken(request, accessToken); if (contentType != null) { request.setRequestProperty("Content-Type", contentType); } if (xmlContent != null) { PrintWriter out = new PrintWriter( new OutputStreamWriter(request.getOutputStream(), UTF_8_CHAR_SET)); out.print(xmlContent); out.flush(); out.close(); } request.connect(); if (request.getResponseCode() != expected) { Error error = readResponse(Error.class, getWrappedInputStream(request.getErrorStream(), GZIP_ENCODING.equalsIgnoreCase(request.getContentEncoding()))); throw createLinkedInApiClientException(error); } else { // return getWrappedInputStream(request.getInputStream(), // GZIP_ENCODING.equalsIgnoreCase(request.getContentEncoding())); InputStream inputStream = getWrappedInputStream(request.getInputStream(), GZIP_ENCODING.equalsIgnoreCase(request.getContentEncoding())); String response = convertStreamToString(inputStream); if (OUTPUT_RESPONSE) { LOG.info("Response: " + response); } } } catch (IOException e) { throw new LinkedInApiClientException(e); } }
From source file:com.irccloud.android.NetworkConnection.java
public Bitmap fetchImage(URL url, boolean cacheOnly) throws Exception { HttpURLConnection conn = null; Proxy proxy = null;/*from w ww . ja v a2 s . co m*/ String host = null; int port = -1; if (Build.VERSION.SDK_INT < 11) { Context ctx = IRCCloudApplication.getInstance().getApplicationContext(); if (ctx != null) { host = android.net.Proxy.getHost(ctx); port = android.net.Proxy.getPort(ctx); } } else { host = System.getProperty("http.proxyHost", null); try { port = Integer.parseInt(System.getProperty("http.proxyPort", "8080")); } catch (NumberFormatException e) { port = -1; } } if (host != null && host.length() > 0 && !host.equalsIgnoreCase("localhost") && !host.equalsIgnoreCase("127.0.0.1") && port > 0) { InetSocketAddress proxyAddr = new InetSocketAddress(host, port); proxy = new Proxy(Proxy.Type.HTTP, proxyAddr); } if (host != null && host.length() > 0 && !host.equalsIgnoreCase("localhost") && !host.equalsIgnoreCase("127.0.0.1") && port > 0) { Crashlytics.log(Log.DEBUG, TAG, "Requesting: " + url + " via proxy: " + host); } else { Crashlytics.log(Log.DEBUG, TAG, "Requesting: " + url); } if (url.getProtocol().toLowerCase().equals("https")) { HttpsURLConnection https = (HttpsURLConnection) ((proxy != null) ? url.openConnection(proxy) : url.openConnection(Proxy.NO_PROXY)); if (url.getHost().equals(IRCCLOUD_HOST)) https.setSSLSocketFactory(IRCCloudSocketFactory); conn = https; } else { conn = (HttpURLConnection) ((proxy != null) ? url.openConnection(proxy) : url.openConnection(Proxy.NO_PROXY)); } conn.setConnectTimeout(30000); conn.setReadTimeout(30000); conn.setUseCaches(true); conn.setRequestProperty("User-Agent", useragent); if (cacheOnly) conn.addRequestProperty("Cache-Control", "only-if-cached"); Bitmap bitmap = null; try { ConnectivityManager cm = (ConnectivityManager) IRCCloudApplication.getInstance() .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo ni = cm.getActiveNetworkInfo(); if (ni != null && ni.getType() == ConnectivityManager.TYPE_WIFI) { Crashlytics.log(Log.DEBUG, TAG, "Loading via WiFi"); } else { Crashlytics.log(Log.DEBUG, TAG, "Loading via mobile"); } } catch (Exception e) { e.printStackTrace(); } try { if (conn.getInputStream() != null) { bitmap = BitmapFactory.decodeStream(conn.getInputStream()); } } catch (FileNotFoundException e) { return null; } catch (IOException e) { e.printStackTrace(); } conn.disconnect(); return bitmap; }
From source file:com.irccloud.android.NetworkConnection.java
public String fetch(URL url, String postdata, String sk, String token, HashMap<String, String> headers) throws Exception { HttpURLConnection conn = null; Proxy proxy = null;// w w w .ja va 2 s.c o m String host = null; int port = -1; if (Build.VERSION.SDK_INT < 11) { Context ctx = IRCCloudApplication.getInstance().getApplicationContext(); if (ctx != null) { host = android.net.Proxy.getHost(ctx); port = android.net.Proxy.getPort(ctx); } } else { host = System.getProperty("http.proxyHost", null); try { port = Integer.parseInt(System.getProperty("http.proxyPort", "8080")); } catch (NumberFormatException e) { port = -1; } } if (host != null && host.length() > 0 && !host.equalsIgnoreCase("localhost") && !host.equalsIgnoreCase("127.0.0.1") && port > 0) { InetSocketAddress proxyAddr = new InetSocketAddress(host, port); proxy = new Proxy(Proxy.Type.HTTP, proxyAddr); } if (host != null && host.length() > 0 && !host.equalsIgnoreCase("localhost") && !host.equalsIgnoreCase("127.0.0.1") && port > 0) { Crashlytics.log(Log.DEBUG, TAG, "Requesting: " + url + " via proxy: " + host); } else { Crashlytics.log(Log.DEBUG, TAG, "Requesting: " + url); } if (url.getProtocol().toLowerCase().equals("https")) { HttpsURLConnection https = (HttpsURLConnection) ((proxy != null) ? url.openConnection(proxy) : url.openConnection(Proxy.NO_PROXY)); if (url.getHost().equals(IRCCLOUD_HOST)) https.setSSLSocketFactory(IRCCloudSocketFactory); conn = https; } else { conn = (HttpURLConnection) ((proxy != null) ? url.openConnection(proxy) : url.openConnection(Proxy.NO_PROXY)); } conn.setConnectTimeout(5000); conn.setReadTimeout(5000); conn.setUseCaches(false); conn.setRequestProperty("User-Agent", useragent); conn.setRequestProperty("Accept", "application/json"); if (headers != null) { for (String key : headers.keySet()) { conn.setRequestProperty(key, headers.get(key)); } } if (sk != null) conn.setRequestProperty("Cookie", "session=" + sk); if (token != null) conn.setRequestProperty("x-auth-formtoken", token); if (postdata != null) { conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); OutputStream ostr = null; try { ostr = conn.getOutputStream(); ostr.write(postdata.getBytes()); } catch (Exception e) { e.printStackTrace(); } finally { if (ostr != null) ostr.close(); } } BufferedReader reader = null; String response = ""; try { ConnectivityManager cm = (ConnectivityManager) IRCCloudApplication.getInstance() .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo ni = cm.getActiveNetworkInfo(); if (ni != null && ni.getType() == ConnectivityManager.TYPE_WIFI) { Crashlytics.log(Log.DEBUG, TAG, "Loading via WiFi"); } else { Crashlytics.log(Log.DEBUG, TAG, "Loading via mobile"); } } catch (Exception e) { } try { if (conn.getInputStream() != null) { reader = new BufferedReader(new InputStreamReader(conn.getInputStream()), 512); } } catch (IOException e) { if (conn.getErrorStream() != null) { reader = new BufferedReader(new InputStreamReader(conn.getErrorStream()), 512); } } if (reader != null) { response = toString(reader); reader.close(); } conn.disconnect(); return response; }