List of usage examples for java.net HttpURLConnection setRequestMethod
public void setRequestMethod(String method) throws ProtocolException
From source file:net.ftb.util.DownloadUtils.java
/** * @param file - the name of the file, as saved to the repo (including extension) * @return - the direct link/*from w ww .j av a 2 s .com*/ */ public static String getStaticCreeperhostLink(String file) { String resolved = (downloadServers.containsKey(Settings.getSettings().getDownloadServer())) ? "http://" + downloadServers.get(Settings.getSettings().getDownloadServer()) : Locations.masterRepo; resolved += "/FTB2/static/" + file; HttpURLConnection connection = null; try { connection = (HttpURLConnection) new URL(resolved).openConnection(); connection.setRequestProperty("Cache-Control", "no-transform"); connection.setRequestMethod("HEAD"); if (connection.getResponseCode() != 200) { for (String server : downloadServers.values()) { if (connection.getResponseCode() != 200) { resolved = "http://" + server + "/FTB2/static/" + file; connection = (HttpURLConnection) new URL(resolved).openConnection(); connection.setRequestProperty("Cache-Control", "no-transform"); connection.setRequestMethod("HEAD"); } else { break; } } } } catch (IOException e) { } connection.disconnect(); return resolved; }
From source file:com.rutarget.UpsourceReviewStatsExtension.PageExtension.java
private static <T> T request(String method, @Nullable Object parameter, Class<T> clazz) throws IOException { String address = UPSOURCE_API_URL + method; URL url = new URL(address); @SuppressWarnings("ConstantConditions") HttpURLConnection c = (HttpURLConnection) (PROXY != null ? url.openConnection(PROXY) : url.openConnection());//from w w w . j av a2 s . c om String authString = UPSOURCE_USERNAME + ":" + UPSOURCE_PASSWORD; //Base64 doesn't look thread safe, therefore we create new instance for each occasion c.setRequestProperty("Authorization", "Basic " + new String(new Base64().encode(authString.getBytes()))); if (parameter != null) { String output = GSON.toJson(parameter); c.setDoOutput(true); c.setRequestMethod("POST"); c.setRequestProperty("Content-Type", "application/json"); c.setRequestProperty("Content-Length", String.valueOf(output.length())); c.getOutputStream().write(output.getBytes("UTF-8")); } InputStream inputStream = c.getInputStream(); String response = IOUtils.toString(inputStream); try { JsonObject element = (JsonObject) new JsonParser().parse(response); return GSON.fromJson(element.get("result"), clazz); } catch (Exception e) { throw new IOException( "Failed to parse response " + escapeToHtmlAttribute(response) + ": " + e.getMessage()); } }
From source file:net.ftb.util.DownloadUtils.java
/** * @param file - the name of the file, as saved to the repo (including extension) * @return - the direct link/*ww w .j a v a 2s .c o m*/ */ public static String getCreeperhostLink(String file) { String resolved = (downloadServers.containsKey(Settings.getSettings().getDownloadServer())) ? "http://" + downloadServers.get(Settings.getSettings().getDownloadServer()) : Locations.masterRepo; resolved += "/FTB2/" + file; HttpURLConnection connection = null; try { connection = (HttpURLConnection) new URL(resolved).openConnection(); connection.setRequestProperty("Cache-Control", "no-transform"); connection.setRequestMethod("HEAD"); for (String server : downloadServers.values()) { if (connection.getResponseCode() != 200) { if (!server.contains("creeper")) { file = file.replaceAll("%5E", "/"); } resolved = "http://" + server + "/FTB2/" + file; connection = (HttpURLConnection) new URL(resolved).openConnection(); connection.setRequestProperty("Cache-Control", "no-transform"); connection.setRequestMethod("HEAD"); } else { break; } } } catch (IOException e) { } connection.disconnect(); return resolved; }
From source file:com.microsoft.azuretools.utils.WebAppUtils.java
public static int sendGet(String sitePath) throws IOException { URL url = new URL(sitePath); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setReadTimeout(Constants.connection_read_timeout_ms); return con.getResponseCode(); //con.setRequestProperty("User-Agent", "AzureTools for Intellij"); }
From source file:com.gmobi.poponews.util.HttpHelper.java
private static Response doRequest(String url, Object raw, int method) { disableSslCheck();/*from w ww . j av a 2 s . co m*/ boolean isJson = raw instanceof JSONObject; String body = raw == null ? null : raw.toString(); Response response = new Response(); HttpURLConnection connection = null; try { URL httpURL = new URL(url); connection = (HttpURLConnection) httpURL.openConnection(); connection.setConnectTimeout(15000); connection.setReadTimeout(30000); connection.setUseCaches(false); if (method == HTTP_POST) connection.setRequestMethod("POST"); if (body != null) { if (isJson) { connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Content-Type", "application/json"); } OutputStream os = connection.getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(os); osw.write(body); osw.flush(); osw.close(); } InputStream in = connection.getInputStream(); response.setBody(FileHelper.readText(in, "UTF-8")); response.setStatusCode(connection.getResponseCode()); in.close(); connection.disconnect(); connection = null; } catch (Exception e) { Logger.error(e); try { if ((connection != null) && (response.getBody() == null) && (connection.getErrorStream() != null)) { response.setBody(FileHelper.readText(connection.getErrorStream(), "UTF-8")); } } catch (Exception ex) { Logger.error(ex); } } return response; }
From source file:br.bireme.tb.URLS.java
/** * Given an url, loads its content (POST - method) * @param url url to be loaded/*from ww w.j av a2 s . co m*/ * @param urlParameters post parameters * @return an array with the real location of the page (in case of redirect) * and its content. * @throws IOException */ public static String[] loadPagePost(final URL url, final String urlParameters) throws IOException { if (url == null) { throw new NullPointerException("url"); } if (urlParameters == null) { throw new NullPointerException("urlParameters"); } final String encodedParams = URLEncoder.encode(urlParameters, DEFAULT_ENCODING); //System.out.print("loading page (POST): [" + url + "] params: " + urlParameters); //Create connection final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", "" + Integer.toString(encodedParams.getBytes().length)); //.getBytes(DEFAULT_ENCODING).length)); connection.setRequestProperty("Content-Language", "pt-BR"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) { wr.write(encodedParams.getBytes(DEFAULT_ENCODING)); //wr.writeBytes(urlParameters); wr.flush(); } //Get Response final StringBuffer response = new StringBuffer(); try (final BufferedReader rd = new BufferedReader( new InputStreamReader(connection.getInputStream(), DEFAULT_ENCODING))) { while (true) { final String line = rd.readLine(); if (line == null) { break; } response.append(line); response.append('\n'); } } connection.disconnect(); return new String[] { url.toString() + "?" + urlParameters, response.toString() }; }
From source file:com.microsoft.azuretools.utils.WebAppUtils.java
public static boolean isUrlAccessible(String url) throws IOException { HttpURLConnection.setFollowRedirects(false); HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection(); con.setRequestMethod("HEAD"); con.setReadTimeout(Constants.connection_read_timeout_ms); try {/*from w ww . j a va 2s . co m*/ if (con.getResponseCode() != HttpURLConnection.HTTP_OK) { return false; } } catch (IOException ex) { return false; } return true; }
From source file:com.androidex.volley.toolbox.HurlStack.java
/** * Perform a multipart request on a connection * /*from www . j ava 2 s .c om*/ * @param connection * The Connection to perform the multi part request * @param request * The params to add to the Multi Part request * The files to upload * @throws ProtocolException */ private static void setConnectionParametersForMultipartRequest(HttpURLConnection connection, Request<?> request) throws IOException, ProtocolException { final String charset = ((MultiPartRequest<?>) request).getProtocolCharset(); final int curTime = (int) (System.currentTimeMillis() / 1000); final String boundary = BOUNDARY_PREFIX + curTime; connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setRequestProperty(HEADER_CONTENT_TYPE, String.format(CONTENT_TYPE_MULTIPART, charset, curTime)); Map<String, MultiPartParam> multipartParams = ((MultiPartRequest<?>) request).getMultipartParams(); Map<String, String> filesToUpload = ((MultiPartRequest<?>) request).getFilesToUpload(); if (((MultiPartRequest<?>) request).isFixedStreamingMode()) { int contentLength = getContentLengthForMultipartRequest(boundary, multipartParams, filesToUpload); connection.setFixedLengthStreamingMode(contentLength); } else { connection.setChunkedStreamingMode(0); } // Modified end ProgressListener progressListener; progressListener = (ProgressListener) request; PrintWriter writer = null; try { OutputStream out = connection.getOutputStream(); writer = new PrintWriter(new OutputStreamWriter(out, charset), true); for (String key : multipartParams.keySet()) { MultiPartParam param = multipartParams.get(key); writer.append(boundary).append(CRLF) .append(String.format(HEADER_CONTENT_DISPOSITION + COLON_SPACE + FORM_DATA, key)) .append(CRLF).append(HEADER_CONTENT_TYPE + COLON_SPACE + param.contentType).append(CRLF) .append(CRLF).append(param.value).append(CRLF).flush(); } for (String key : filesToUpload.keySet()) { File file = new File(filesToUpload.get(key)); if (!file.exists()) { throw new IOException(String.format("File not found: %s", file.getAbsolutePath())); } if (file.isDirectory()) { throw new IOException(String.format("File is a directory: %s", file.getAbsolutePath())); } writer.append(boundary).append(CRLF) .append(String.format( HEADER_CONTENT_DISPOSITION + COLON_SPACE + FORM_DATA + SEMICOLON_SPACE + FILENAME, key, file.getName())) .append(CRLF).append(HEADER_CONTENT_TYPE + COLON_SPACE + CONTENT_TYPE_OCTET_STREAM) .append(CRLF).append(HEADER_CONTENT_TRANSFER_ENCODING + COLON_SPACE + BINARY).append(CRLF) .append(CRLF).flush(); BufferedInputStream input = null; try { FileInputStream fis = new FileInputStream(file); int transferredBytes = 0; int totalSize = (int) file.length(); input = new BufferedInputStream(fis); int bufferLength = 0; byte[] buffer = new byte[1024]; while ((bufferLength = input.read(buffer)) > 0) { out.write(buffer, 0, bufferLength); transferredBytes += bufferLength; progressListener.onProgress(transferredBytes, totalSize); } out.flush(); // Important! Output cannot be closed. Close of // writer will close // output as well. } finally { if (input != null) try { input.close(); } catch (IOException ex) { ex.printStackTrace(); } } writer.append(CRLF).flush(); // CRLF is important! It indicates // end of binary // boundary. } // End of multipart/form-data. writer.append(boundary + BOUNDARY_PREFIX).append(CRLF).flush(); } catch (Exception e) { e.printStackTrace(); } finally { if (writer != null) { writer.close(); } } }
From source file:com.volley.air.toolbox.HurlStack.java
/** * Perform a multipart request on a connection * /*from w w w. ja v a 2 s . c o m*/ * @param connection * The Connection to perform the multi part request * @param request * The params to add to the Multi Part request * The files to upload * @throws ProtocolException */ private static void setConnectionParametersForMultipartRequest(HttpURLConnection connection, Request<?> request) throws IOException, ProtocolException { final String charset = ((MultiPartRequest<?>) request).getProtocolCharset(); final int curTime = (int) (System.currentTimeMillis() / 1000); final String boundary = BOUNDARY_PREFIX + curTime; connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setRequestProperty(HEADER_CONTENT_TYPE, String.format(CONTENT_TYPE_MULTIPART, charset, curTime)); Map<String, MultiPartParam> multipartParams = ((MultiPartRequest<?>) request).getMultipartParams(); Map<String, String> filesToUpload = ((MultiPartRequest<?>) request).getFilesToUpload(); if (((MultiPartRequest<?>) request).isFixedStreamingMode()) { int contentLength = getContentLengthForMultipartRequest(boundary, multipartParams, filesToUpload); connection.setFixedLengthStreamingMode(contentLength); } else { connection.setChunkedStreamingMode(0); } // Modified end ProgressListener progressListener; progressListener = (ProgressListener) request; PrintWriter writer = null; try { OutputStream out = connection.getOutputStream(); writer = new PrintWriter(new OutputStreamWriter(out, charset), true); for (Entry<String, MultiPartParam> entry : multipartParams.entrySet()) { MultiPartParam param = entry.getValue(); writer.append(boundary).append(CRLF) .append(String.format(HEADER_CONTENT_DISPOSITION + COLON_SPACE + FORM_DATA, entry.getKey())) .append(CRLF).append(HEADER_CONTENT_TYPE + COLON_SPACE + param.contentType).append(CRLF) .append(CRLF).append(param.value).append(CRLF).flush(); } for (Entry<String, String> entry : filesToUpload.entrySet()) { File file = new File(entry.getValue()); if (!file.exists()) { throw new IOException(String.format("File not found: %s", file.getAbsolutePath())); } if (file.isDirectory()) { throw new IOException(String.format("File is a directory: %s", file.getAbsolutePath())); } writer.append(boundary).append(CRLF) .append(String.format( HEADER_CONTENT_DISPOSITION + COLON_SPACE + FORM_DATA + SEMICOLON_SPACE + FILENAME, entry.getKey(), file.getName())) .append(CRLF).append(HEADER_CONTENT_TYPE + COLON_SPACE + CONTENT_TYPE_OCTET_STREAM) .append(CRLF).append(HEADER_CONTENT_TRANSFER_ENCODING + COLON_SPACE + BINARY).append(CRLF) .append(CRLF).flush(); BufferedInputStream input = null; try { FileInputStream fis = new FileInputStream(file); int transferredBytes = 0; int totalSize = (int) file.length(); input = new BufferedInputStream(fis); int bufferLength; byte[] buffer = new byte[1024]; while ((bufferLength = input.read(buffer)) > 0) { out.write(buffer, 0, bufferLength); transferredBytes += bufferLength; progressListener.onProgress(transferredBytes, totalSize); } out.flush(); // Important! Output cannot be closed. Close of // writer will close // output as well. } finally { if (input != null) try { input.close(); } catch (IOException ex) { ex.printStackTrace(); } } writer.append(CRLF).flush(); // CRLF is important! It indicates // end of binary // boundary. } // End of multipart/form-data. writer.append(boundary + BOUNDARY_PREFIX).append(CRLF).flush(); } catch (Exception e) { e.printStackTrace(); } finally { if (writer != null) { writer.close(); } } }
From source file:com.example.pabrto.AppEngineClient.java
public static int delete(URL uri, Map<String, List<String>> headers) { //DELETE delete = new DELETE(uri, headers); int s = 0;//w w w. j a va2 s. co m HttpURLConnection httpURLConnection = null; try { httpURLConnection = (HttpURLConnection) uri.openConnection(); if (headers != null) { for (String header : headers.keySet()) { for (String value : headers.get(header)) { httpURLConnection.addRequestProperty(header, value); } } } httpURLConnection.setRequestMethod("DELETE"); //httpURLConnection.connect(); s = httpURLConnection.getResponseCode(); Log.d("TAG", "Response of delete: " + String.valueOf(s)); } catch (IOException exception) { exception.printStackTrace(); } finally { if (httpURLConnection != null) { httpURLConnection.disconnect(); } } return s; }