List of usage examples for java.net HttpURLConnection addRequestProperty
public void addRequestProperty(String key, String value)
From source file:org.alfresco.repo.web.scripts.tenant.TenantAdminSystemTest.java
private static String callInOutWeb(String urlString, String method, String ticket, String data, String contentType, String soapAction) throws MalformedURLException, URISyntaxException, IOException { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(method);//from w w w . j av a 2s .co m conn.setRequestProperty("Content-type", contentType); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); if (soapAction != null) { conn.setRequestProperty("SOAPAction", soapAction); } if (ticket != null) { // add Base64 encoded authorization header // refer to: http://wiki.alfresco.com/wiki/Web_Scripts_Framework#HTTP_Basic_Authentication conn.addRequestProperty("Authorization", "Basic " + Base64.encodeBytes(ticket.getBytes())); } String result = null; BufferedReader br = null; DataOutputStream wr = null; OutputStream os = null; InputStream is = null; try { os = conn.getOutputStream(); wr = new DataOutputStream(os); wr.write(data.getBytes()); wr.flush(); } finally { if (wr != null) { wr.close(); } ; if (os != null) { os.close(); } ; } try { is = conn.getInputStream(); br = new BufferedReader(new InputStreamReader(is)); String line = null; StringBuffer sb = new StringBuffer(); while (((line = br.readLine()) != null)) { sb.append(line); } result = sb.toString(); } finally { if (br != null) { br.close(); } ; if (is != null) { is.close(); } ; } return result; }
From source file:io.sloeber.core.managers.Manager.java
/** * copy a url locally taking into account redirections * * @param url/*w w w . j a va 2s .c om*/ * @param localFile */ @SuppressWarnings("nls") private static void myCopy(URL url, File localFile) { try { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(5000); conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8"); conn.addRequestProperty("User-Agent", "Mozilla"); conn.addRequestProperty("Referer", "google.com"); // normally, 3xx is redirect int status = conn.getResponseCode(); if (status != HttpURLConnection.HTTP_OK) { if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER) Files.copy(new URL(conn.getHeaderField("Location")).openStream(), localFile.toPath(), REPLACE_EXISTING); } else { Files.copy(url.openStream(), localFile.toPath(), REPLACE_EXISTING); } } catch (Exception e) { Common.log(new Status(IStatus.WARNING, Activator.getId(), "Failed to download url " + url, e)); } }
From source file:com.example.httpjson.AppEngineClient.java
public static Response getOrPost(Request request) { mErrorMessage = null;/*from w ww.j a v a 2 s . c o m*/ HttpURLConnection conn = null; Response response = null; try { conn = (HttpURLConnection) request.uri.openConnection(); // if (!mAuthenticator.authenticate(conn)) { // mErrorMessage = str(R.string.aerc_authentication_failed) + ": " + mAuthenticator.errorMessage(); // } else { if (request.headers != null) { for (String header : request.headers.keySet()) { for (String value : request.headers.get(header)) { conn.addRequestProperty(header, value); } } } if (request instanceof POST) { byte[] payload = ((POST) request).body; String s = new String(payload, "UTF-8"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); JSONObject jsonobj = getJSONObject(s); conn.setRequestProperty("Content-Type", "application/json; charset=utf8"); // ... OutputStream os = conn.getOutputStream(); os.write(jsonobj.toString().getBytes("UTF-8")); os.close(); // conn.setFixedLengthStreamingMode(payload.length); // conn.getOutputStream().write(payload); int status = conn.getResponseCode(); if (status / 100 != 2) response = new Response(status, new Hashtable<String, List<String>>(), conn.getResponseMessage().getBytes()); } if (response == null) { int a = conn.getResponseCode(); if (a == 401) { response = new Response(a, conn.getHeaderFields(), new byte[] {}); } InputStream a1 = conn.getErrorStream(); BufferedInputStream in = new BufferedInputStream(conn.getInputStream()); byte[] body = readStream(in); response = new Response(conn.getResponseCode(), conn.getHeaderFields(), body); // List<String> a = conn.getHeaderFields().get("aa"); } } } catch (IOException e) { e.printStackTrace(System.err); mErrorMessage = ((request instanceof POST) ? "POST " : "GET ") + str(R.string.aerc_failed) + ": " + e.getLocalizedMessage(); } finally { if (conn != null) conn.disconnect(); } return response; }
From source file:com.fivehundredpxdemo.android.storage.ImageFetcher.java
/** * Download a bitmap from a URL, write it to a disk and return the File pointer. This * implementation uses a simple disk cache. * * @param urlString The URL to fetch//from w w w . j a v a2 s. c o m * @param cacheDir The directory to store the downloaded file * @return A File pointing to the fetched bitmap */ public static File downloadBitmapToFile(String urlString, File cacheDir, String accessToken) { Log.d(TAG, "downloadBitmap - downloading - " + urlString); disableConnectionReuseIfNecessary(); HttpURLConnection urlConnection = null; BufferedOutputStream out = null; BufferedInputStream in = null; try { final File tempFile = File.createTempFile("bitmap", null, cacheDir); final URL url = new URL(urlString); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.addRequestProperty("Authorization", "Bearer " + accessToken); if (urlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) { return null; } in = new BufferedInputStream(urlConnection.getInputStream(), IO_BUFFER_SIZE_BYTES); out = new BufferedOutputStream(new FileOutputStream(tempFile), IO_BUFFER_SIZE_BYTES); int b; while ((b = in.read()) != -1) { out.write(b); } return tempFile; } catch (final IOException e) { Log.e(TAG, "Error in downloadBitmap - " + e); } finally { if (urlConnection != null) { urlConnection.disconnect(); } try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (final IOException e) { } } return null; }
From source file:com.example.pabrto.AppEngineClient.java
public static Response getOrPost(Request request) { mErrorMessage = null;//from ww w.j av a 2 s. com HttpURLConnection conn = null; Response response = null; try { conn = (HttpURLConnection) request.uri.openConnection(); // if (!mAuthenticator.authenticate(conn)) { // mErrorMessage = str(R.string.aerc_authentication_failed) + ": " + mAuthenticator.errorMessage(); // } else { if (request.headers != null) { for (String header : request.headers.keySet()) { for (String value : request.headers.get(header)) { conn.addRequestProperty(header, value); } } } if (request instanceof POST) { byte[] payload = ((POST) request).body; String s = new String(payload, "UTF-8"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); JSONObject jsonobj = getJSONObject(s); conn.setRequestProperty("Content-Type", "application/json; charset=utf8"); // ... OutputStream os = conn.getOutputStream(); os.write(jsonobj.toString().getBytes("UTF-8")); os.close(); // conn.setFixedLengthStreamingMode(payload.length); // conn.getOutputStream().write(payload); int status = conn.getResponseCode(); if (status / 100 != 2) response = new Response(status, new Hashtable<String, List<String>>(), conn.getResponseMessage().getBytes()); } if (response == null) { int a = conn.getResponseCode(); InputStream a1 = conn.getErrorStream(); BufferedInputStream in = new BufferedInputStream(conn.getInputStream()); byte[] body = readStream(in); response = new Response(conn.getResponseCode(), conn.getHeaderFields(), body); // List<String> a = conn.getHeaderFields().get("aa"); } } } catch (IOException e) { e.printStackTrace(System.err); mErrorMessage = ((request instanceof POST) ? "POST " : "GET ") + str(R.string.aerc_failed) + ": " + e.getLocalizedMessage(); } finally { if (conn != null) conn.disconnect(); } return response; }
From source file:com.example.rtobase2.AppEngineClient.java
public static Response getOrPost(Request request) { mErrorMessage = null;//w w w . ja v a2 s .c o m HttpURLConnection conn = null; Response response = null; try { conn = (HttpURLConnection) request.uri.openConnection(); // if (!mAuthenticator.authenticate(conn)) { // mErrorMessage = str(R.string.aerc_authentication_failed) + ": " + mAuthenticator.errorMessage(); // } else { if (request.headers != null) { for (String header : request.headers.keySet()) { for (String value : request.headers.get(header)) { conn.addRequestProperty(header, value); } } } if (request instanceof PUT) { byte[] payload = ((PUT) request).body; String s = new String(payload, "UTF-8"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("PUT"); JSONObject jsonobj = getJSONObject(s); conn.setRequestProperty("Content-Type", "application/json; charset=utf8"); OutputStream os = conn.getOutputStream(); os.write(jsonobj.toString().getBytes("UTF-8")); os.close(); } if (request instanceof POST) { byte[] payload = ((POST) request).body; String s = new String(payload, "UTF-8"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); JSONObject jsonobj = getJSONObject(s); conn.setRequestProperty("Content-Type", "application/json; charset=utf8"); // ... OutputStream os = conn.getOutputStream(); os.write(jsonobj.toString().getBytes("UTF-8")); os.close(); // conn.setFixedLengthStreamingMode(payload.length); // conn.getOutputStream().write(payload); int status = conn.getResponseCode(); if (status / 100 != 2) response = new Response(status, new Hashtable<String, List<String>>(), conn.getResponseMessage().getBytes()); } if (response == null) { BufferedInputStream in = new BufferedInputStream(conn.getInputStream()); byte[] body = readStream(in); response = new Response(conn.getResponseCode(), conn.getHeaderFields(), body); // List<String> a = conn.getHeaderFields().get("aa"); } } } catch (IOException e) { e.printStackTrace(System.err); mErrorMessage = ((request instanceof POST) ? "POST " : "GET ") + str(R.string.aerc_failed) + ": " + e.getLocalizedMessage(); } finally { if (conn != null) conn.disconnect(); } return response; }
From source file:com.ab.network.toolbox.HurlStack.java
@SuppressWarnings("deprecation") /* package */ static void setConnectionParametersForRequest(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { switch (request.getMethod()) { case Method.DEPRECATED_GET_OR_POST: // This is the deprecated way that needs to be handled for backwards compatibility. // If the request's post body is null, then the assumption is that the request is // GET. Otherwise, it is assumed that the request is a POST. byte[] postBody = request.getPostBody(); if (postBody != null) { // Prepare output. There is no need to set Content-Length explicitly, // since this is handled by HttpURLConnection using the size of the prepared // output stream. connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getPostBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(postBody);//from w ww . ja v a2 s .c o m out.close(); } break; case Method.GET: // Not necessary to set the request method because connection defaults to GET but // being explicit here. connection.setRequestMethod("GET"); break; case Method.DELETE: connection.setRequestMethod("DELETE"); break; case Method.POST: connection.setRequestMethod("POST"); addBodyIfExists(connection, request); break; case Method.PUT: connection.setRequestMethod("PUT"); addBodyIfExists(connection, request); break; default: throw new IllegalStateException("Unknown method type."); } }
From source file:com.wudoumi.batter.volley.toolbox.HurlStack.java
@SuppressWarnings("deprecation") /* package */ static void setConnectionParametersForRequest(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { switch (request.getMethod()) { case RequestType.DEPRECATED_GET_OR_POST: // This is the deprecated way that needs to be handled for backwards compatibility. // If the request's post body is null, then the assumption is that the request is // GET. Otherwise, it is assumed that the request is a POST. byte[] postBody = request.getPostBody(); if (postBody != null) { // Prepare output. There is no need to set Content-Length explicitly, // since this is handled by HttpURLConnection using the size of the prepared // output stream. connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getPostBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(postBody);//from w ww .j a v a 2 s . c om out.close(); } break; case RequestType.GET: // Not necessary to set the request method because connection defaults to GET but // being explicit here. connection.setRequestMethod("GET"); break; case RequestType.DELETE: connection.setRequestMethod("DELETE"); break; case RequestType.POST: connection.setRequestMethod("POST"); addBodyIfExists(connection, request); break; case RequestType.PUT: connection.setRequestMethod("PUT"); addBodyIfExists(connection, request); break; default: throw new IllegalStateException("Unknown method type."); } }
From source file:com.volley.android.toolbox.HurlStack.java
@SuppressWarnings("deprecation") /* package */ static void setConnectionParametersForRequest(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { switch (request.getMethod()) { case Request.Method.DEPRECATED_GET_OR_POST: // This is the deprecated way that needs to be handled for backwards compatibility. // If the request's post body is null, then the assumption is that the request is // GET. Otherwise, it is assumed that the request is a POST. byte[] postBody = request.getPostBody(); if (postBody != null) { // Prepare output. There is no need to set Content-Length explicitly, // since this is handled by HttpURLConnection using the size of the prepared // output stream. connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getPostBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(postBody);//from w w w .ja v a 2 s . c o m out.close(); } break; case Request.Method.GET: // Not necessary to set the request method because connection defaults to GET but // being explicit here. connection.setRequestMethod("GET"); break; case Request.Method.DELETE: connection.setRequestMethod("DELETE"); break; case Request.Method.POST: connection.setRequestMethod("POST"); addBodyIfExists(connection, request); break; case Request.Method.PUT: connection.setRequestMethod("PUT"); addBodyIfExists(connection, request); break; default: throw new IllegalStateException("Unknown method type."); } }
From source file:com.autonavi.gxdtaojin.toolbox.HurlStack.java
@SuppressWarnings("deprecation") /* package */static void setConnectionParametersForRequest(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { switch (request.getMethod()) { case Method.DEPRECATED_GET_OR_POST: // This is the deprecated way that needs to be handled for backwards compatibility. // If the request's post body is null, then the assumption is that the request is // GET. Otherwise, it is assumed that the request is a POST. byte[] postBody = request.getPostBody(); if (postBody != null) { // Prepare output. There is no need to set Content-Length explicitly, // since this is handled by HttpURLConnection using the size of the prepared // output stream. connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getPostBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(postBody);/*from w ww . j a v a 2 s. co m*/ out.close(); } break; case Method.GET: // Not necessary to set the request method because connection defaults to GET but // being explicit here. connection.setRequestMethod("GET"); break; case Method.DELETE: connection.setRequestMethod("DELETE"); break; case Method.POST: connection.setRequestMethod("POST"); addBodyIfExists(connection, request); break; case Method.PUT: connection.setRequestMethod("PUT"); addBodyIfExists(connection, request); break; default: throw new IllegalStateException("Unknown method type."); } }