List of usage examples for org.apache.http.protocol HTTP CONTENT_TYPE
String CONTENT_TYPE
To view the source code for org.apache.http.protocol HTTP CONTENT_TYPE.
Click Source Link
From source file:edu.pdx.its.portal.routelandia.ApiPoster.java
public JSONObject postJsonObjectToUrl(String url, JSONObject jsonObject, APIResultWrapper retVal) { InputStream inputStream = null; String result = ""; try {//from w ww. jav a 2 s .c o m // 1. create HttpClient HttpClient httpclient = new DefaultHttpClient(); // 2. make POST request to the given URL //http://capstoneaa.cs.pdx.edu/api/trafficstats HttpPost httpPost = new HttpPost(url); // 4. convert JSONObject to JSON to String String json = jsonObject.toString(); // 5. set json to StringEntity StringEntity se = new StringEntity(json); se.setContentType("application/json;charset=UTF-8"); se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8")); // 6. set httpPost Entity httpPost.setEntity(se); // 7. Set some headers to inform server about the type of the content // httpPost.setHeader("Accept", "application/json"); // httpPost.setHeader("Content-type", "application/json"); // 8. Execute POST request to the given URL HttpResponse httpResponse = httpclient.execute(httpPost); // Make sure we've got a good response from the API. int status = httpResponse.getStatusLine().getStatusCode(); retVal.setHttpStatus(status); result = EntityUtils.toString(httpResponse.getEntity()); //Log.i("RAW HTTP RESULT", result); retVal.setRawResponse(result); } catch (Exception e) { Log.e("InputStream", e.getLocalizedMessage()); } try { Object json = new JSONTokener(result).nextValue(); if (json instanceof JSONObject) { retVal.setParsedResponse((JSONObject) json); return (JSONObject) json; } } catch (JSONException e) { e.printStackTrace(); } // If we got this far, we got something very wrong... Log.e(TAG, "Didn't get a valid JSON response!"); return null; }
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 w w . jav a2 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 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.sckftr.android.utils.net.Network.java
/** * Call the webservice using the given parameters to construct the request and return the * result./*from w w w . j a va 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 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.zextras.zimbradrive.UploadFileHttpHandler.java
private HttpResponse uploadFileToDrive(HttpServletRequest httpServletRequest) throws IOException { String formBoundary = getFormPartsBoundary(httpServletRequest); Account userAccount = mBackendUtils.assertAccountFromAuthToken(httpServletRequest); ZimbraLog.addAccountNameToContext(userAccount.getName()); HttpEntity requestToSendToDrive = createUploadFileRequest(httpServletRequest, formBoundary, userAccount); String driveOnCloudDomain = mDriveProxy.getDriveDomainAssociatedToDomain(userAccount.getDomainName()); String fileUploadRequestUrl = driveOnCloudDomain + NEXT_CLOUD_UPLOAD_FILE_URL; HttpPost post = new HttpPost(fileUploadRequestUrl); post.setEntity(requestToSendToDrive); post.setHeader(HTTP.CONTENT_TYPE, "multipart/form-data; boundary=" + formBoundary); HttpClient client = HttpClientBuilder.create().build(); return client.execute(post); }
From source file:ste.web.http.beanshell.BugFreeBeanShellUtils.java
@Test public void bodyAsJSONObject() throws Exception { final String TEST_LABEL1 = "label1"; final String TEST_LABEL2 = "label2"; final String TEST_VALUE1 = "a first label"; final String TEST_VALUE2 = "a second label"; BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("get", TEST_URI_PARAMETERS); HttpSessionContext context = new HttpSessionContext(); context.setAttribute(HttpCoreContext.HTTP_CONNECTION, getConnection()); request.addHeader(HTTP.CONTENT_TYPE, CONTENT_TYPE_JSON); request.setEntity(new StringEntity(String.format("{%s:'%s'}", TEST_LABEL1, TEST_VALUE1))); Interpreter i = new Interpreter(); BeanShellUtils.setup(i, request, RESPONSE_OK, context); checkJSONObject(i, TEST_LABEL1, TEST_VALUE1); request.setEntity(new StringEntity( String.format("[{%s:'%s'}, {%s:'%s'}]", TEST_LABEL1, TEST_VALUE1, TEST_LABEL2, TEST_VALUE2))); BeanShellUtils.setup(i, request, RESPONSE_OK, context); checkJSONArray(i, new String[] { TEST_LABEL1, TEST_LABEL2 }, new String[] { TEST_VALUE1, TEST_VALUE2 }); }
From source file:core.AbstractTest.java
private int httpRequest(String sUrl, String sMethod, JsonNode payload, Map<String, String> mParameters) { Logger.info("\n\nREQUEST:\n" + sMethod + " " + sUrl + "\nHEADERS: " + mHeaders + "\nParameters: " + mParameters + "\nPayload: " + payload + "\n"); HttpURLConnection conn = null; BufferedReader br = null;/* w w w. ja va2s . c o m*/ int nRet = 0; boolean fIsMultipart = false; try { setStatusCode(-1); setResponse(null); conn = getHttpConnection(sUrl, sMethod); if (mHeaders.size() > 0) { Set<String> keys = mHeaders.keySet(); for (String sKey : keys) { conn.addRequestProperty(sKey, mHeaders.get(sKey)); if (sKey.equals(HTTP.CONTENT_TYPE)) { if (mHeaders.get(sKey).startsWith(MediaType.MULTIPART_FORM_DATA)) { fIsMultipart = true; } } } } if (payload != null || mParameters != null) { DataOutputStream out = new DataOutputStream(conn.getOutputStream()); try { if (payload != null) { //conn.setRequestProperty("Content-Length", "" + node.toString().length()); out.writeBytes(payload.toString()); } if (mParameters != null) { Set<String> sKeys = mParameters.keySet(); if (fIsMultipart) { out.writeBytes("--" + BOUNDARY + "\r\n"); } for (String sKey : sKeys) { if (fIsMultipart) { out.writeBytes("Content-Disposition: form-data; name=\"" + sKey + "\"\r\n\r\n"); out.writeBytes(mParameters.get(sKey)); out.writeBytes("\r\n"); out.writeBytes("--" + BOUNDARY + "--\r\n"); } else { out.writeBytes(URLEncoder.encode(sKey, "UTF-8")); out.writeBytes("="); out.writeBytes(URLEncoder.encode(mParameters.get(sKey), "UTF-8")); out.writeBytes("&"); } } if (fIsMultipart) { if (nvpFile != null) { File f = Play.application().getFile(nvpFile.getName()); if (f == null) { assertFail("Cannot find file <" + nvpFile.getName() + ">"); } FileBody fb = new FileBody(f); out.writeBytes("Content-Disposition: form-data; name=\"" + PARAM_FILE + "\";filename=\"" + fb.getFilename() + "\"\r\n"); out.writeBytes("Content-Type: " + nvpFile.getValue() + "\r\n\r\n"); out.write(getResource(nvpFile.getName())); } out.writeBytes("\r\n--" + BOUNDARY + "--\r\n"); } } } catch (Exception ex) { assertFail("Send request: " + ex.getMessage()); } finally { try { out.flush(); } catch (Exception ex) { } try { out.close(); } catch (Exception ex) { } } } nRet = conn.getResponseCode(); setStatusCode(nRet); if (nRet / 100 != 2) { if (conn.getErrorStream() != null) { br = new BufferedReader(new InputStreamReader(conn.getErrorStream())); } } else { if (conn.getInputStream() != null) { br = new BufferedReader(new InputStreamReader(conn.getInputStream())); } } if (br != null) { String temp = null; StringBuilder sb = new StringBuilder(1024); while ((temp = br.readLine()) != null) { sb.append(temp).append("\n"); } setResponse(sb.toString().trim()); } Logger.info("\nRESPONSE\nHTTP code: " + nRet + "\nContent: " + sResponse + "\n"); } catch (Exception ex) { assertFail("httpRequest: " + ex.getMessage()); } finally { if (br != null) { try { br.close(); } catch (Exception ex) { } } if (conn != null) { conn.disconnect(); } } return nRet; }
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 w ww . ja v a 2 s . co 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:de.azapps.mirakel.sync.Network.java
private String downloadUrl(String myurl) throws IOException, URISyntaxException { if (token != null) { myurl += "?authentication_key=" + token; }/*from ww w . j av a2 s . c om*/ if (myurl.indexOf("https") == -1) { Integer[] t = { NoHTTPS }; publishProgress(t); } /* * String authorizationString = null; * if (syncTyp == ACCOUNT_TYPES.CALDAV) { * authorizationString = "Basic " * + Base64.encodeToString( * (username + ":" + password).getBytes(), * Base64.NO_WRAP); * } */ CredentialsProvider credentials = new BasicCredentialsProvider(); credentials.setCredentials(new AuthScope(new URI(myurl).getHost(), -1), new UsernamePasswordCredentials(username, password)); HttpParams params = new BasicHttpParams(); params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpConnectionParams.setTcpNoDelay(params, true); HttpClient httpClient; /* * if(syncTyp == ACCOUNT_TYPES.MIRAKEL) * httpClient = sslClient(client); * else { */ DefaultHttpClient tmpHttpClient = new DefaultHttpClient(params); tmpHttpClient.setCredentialsProvider(credentials); httpClient = tmpHttpClient; // } httpClient.getParams().setParameter("http.protocol.content-charset", HTTP.UTF_8); HttpResponse response; try { switch (mode) { case GET: Log.v(TAG, "GET " + myurl); HttpGet get = new HttpGet(); get.setURI(new URI(myurl)); response = httpClient.execute(get); break; case PUT: Log.v(TAG, "PUT " + myurl); HttpPut put = new HttpPut(); if (syncTyp == ACCOUNT_TYPES.CALDAV) { put.addHeader(HTTP.CONTENT_TYPE, "text/calendar; charset=utf-8"); } put.setURI(new URI(myurl)); put.setEntity(new StringEntity(content, HTTP.UTF_8)); Log.v(TAG, content); response = httpClient.execute(put); break; case POST: Log.v(TAG, "POST " + myurl); HttpPost post = new HttpPost(); post.setURI(new URI(myurl)); post.setEntity(new UrlEncodedFormEntity(headerData, HTTP.UTF_8)); response = httpClient.execute(post); break; case DELETE: Log.v(TAG, "DELETE " + myurl); HttpDelete delete = new HttpDelete(); delete.setURI(new URI(myurl)); response = httpClient.execute(delete); break; case REPORT: Log.v(TAG, "REPORT " + myurl); HttpReport report = new HttpReport(); report.setURI(new URI(myurl)); Log.d(TAG, content); report.setEntity(new StringEntity(content, HTTP.UTF_8)); response = httpClient.execute(report); break; default: Log.wtf("HTTP-MODE", "Unknown Http-Mode"); return null; } } catch (Exception e) { Log.e(TAG, "No Networkconnection available"); Log.w(TAG, Log.getStackTraceString(e)); return ""; } Log.v(TAG, "Http-Status: " + response.getStatusLine().getStatusCode()); if (response.getEntity() == null) return ""; String r = EntityUtils.toString(response.getEntity(), HTTP.UTF_8); Log.d(TAG, r); return r; }
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./* w w w. j a v a 2s. 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, 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(); } } }