Java Code Examples for java.net.HttpURLConnection#setRequestMethod()
The following examples show how to use
java.net.HttpURLConnection#setRequestMethod() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: InfluxDBUtil.java From jumbune with GNU Lesser General Public License v3.0 | 6 votes |
/** * Create database in influxdb according to configuration provided * * @param configuration * @throws Exception */ public static void createRetentionPolicy(InfluxDBConf configuration) { try { StringBuffer url = new StringBuffer(); url.append(HTTP).append(configuration.getHost().trim()).append(COLON) .append(configuration.getPort()).append("/query?u=") .append(configuration.getUsername()).append(AND_P_EQUAL_TO) .append(configuration.getDecryptedPassword()).append(AND_Q_EQUAL_TO) .append("CREATE%20RETENTION%20POLICY%20ret_" + configuration.getDatabase() + "%20on%20" + configuration .getDatabase() + "%20DURATION%2090d%20REPLICATION%201%20DEFAULT"); URL obj = new URL(url.toString()); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod(GET); con.setRequestProperty(USER_AGENT, MOZILLA_5_0); con.getContent(); con.disconnect(); } catch (Exception e) { LOGGER.error("Unable to create retention policy in influxdata for database + " + configuration.getDatabase()); } }
Example 2
Source File: NetUtil.java From live-chat-engine with Apache License 2.0 | 6 votes |
public static HttpURLConnection openPostConn(String url, int connTimeout, int readTimeout) throws IOException { HttpURLConnection conn = (HttpURLConnection)new URL(url).openConnection(); conn.setConnectTimeout(connTimeout); conn.setReadTimeout(readTimeout); conn.setUseCaches(false); conn.setDoInput(true); conn.setRequestMethod("POST"); String agent = System.getProperty("http.agent"); if(hasText(agent)){ conn.setRequestProperty("User-Agent", agent); } return conn; }
Example 3
Source File: YarnContainerHealthMonitor.java From dremio-oss with Apache License 2.0 | 6 votes |
/** * Method to make the HTTP call and log the state of the container */ private void isContainerHealthy() { try { URL url = new URL(nodeManagerURL); Stopwatch stopwatch = Stopwatch.createStarted(); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); String currentContainerState = getContainerState(connection); if (currentContainerState == null) { logger.error("Container with id: {} does not exist!", containerID); return; } stopwatch.stop(); logger.debug("Retrieving container state from NodeManager URL: {} took {} microseconds with response code {}", nodeManagerURL, stopwatch.elapsed(TimeUnit.MICROSECONDS), connection.getResponseCode()); if (!currentContainerState.equals(previousContainerState)) { logger.info("Container state changed. Previous: {}, Current: {}", previousContainerState, currentContainerState); previousContainerState = currentContainerState; } } catch (IOException e) { if (!e.getCause().equals(exception)) { logger.error("Error occurred while connecting to NodeManager!", e); exception = e.getCause(); } } }
Example 4
Source File: MendeleyClient.java From slr-toolkit with Eclipse Public License 1.0 | 5 votes |
/** * This methods is used to obtain all BibTeXEntries of a Mendeley Document via the GET https://api.mendeley.com/documents/{id} endpoint. * * @param id Document ID tha is stored in Mendeley Folder. * @return This Method returns a BibTeXDatabase of the given document id * @throws MalformedURLException * @throws IOException * @throws TokenMgrException * @throws ParseException */ public BibTeXDatabase getDocumentBibTex(String id) throws MalformedURLException, IOException, TokenMgrException, ParseException{ refreshTokenIfNecessary(); String resource_url = "https://api.mendeley.com/documents/" + id + "?view=bib&limit=500"; HttpURLConnection resource_cxn = (HttpURLConnection)(new URL(resource_url).openConnection()); resource_cxn.addRequestProperty("Authorization", "Bearer " + this.access_token); resource_cxn.setRequestMethod("GET"); resource_cxn.setRequestProperty("Accept","application/x-bibtex"); InputStream resource = resource_cxn.getInputStream(); BufferedReader r = new BufferedReader(new InputStreamReader(resource, "UTF-8")); BibTeXDatabase db = new BibTeXDatabase(); try(Reader reader = r){ CharacterFilterReader filterReader = new CharacterFilterReader(reader); BibTeXParser parser = new BibTeXParser(); db = parser.parse(filterReader); /* * Mendeley API returns a parsing error concerning the 'title' field * - The additional characters '{' at the beginning of a Title and '}' at the end of a title * must be removed */ for(BibTeXEntry entry: db.getEntries().values()){ String fixedTitleStr = getFixedString(entry.getField(new Key("title")).toUserString()); StringValue fixedTitleValue = new StringValue(fixedTitleStr, StringValue.Style.BRACED); entry.removeField(new Key("title")); entry.addField(new Key("title"), fixedTitleValue); } }catch (TokenMgrException | IOException |ParseException e) { e.printStackTrace(); } return db; }
Example 5
Source File: HeadTest.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
static void runClient(String urlStr) throws Exception { HttpURLConnection conn = (HttpURLConnection) new URL(urlStr).openConnection(); conn.setRequestMethod("HEAD"); int status = conn.getResponseCode(); if (status != 200) { throw new RuntimeException("HEAD request doesn't return 200, but returns " + status); } }
Example 6
Source File: WSUrlFetch.java From restcommander with Apache License 2.0 | 5 votes |
private HttpURLConnection prepare(URL url, String method) { if (this.username != null && this.password != null && this.scheme != null) { String authString = null; switch (this.scheme) { case BASIC: authString = basicAuthHeader(); break; default: throw new RuntimeException("Scheme " + this.scheme + " not supported by the UrlFetch WS backend."); } this.headers.put("Authorization", authString); } try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(method); connection.setDoInput(true); connection.setInstanceFollowRedirects(this.followRedirects); connection.setReadTimeout(this.timeout * 1000); for (String key: this.headers.keySet()) { connection.setRequestProperty(key, headers.get(key)); } checkFileBody(connection); if (this.oauthToken != null && this.oauthSecret != null) { OAuthConsumer consumer = new DefaultOAuthConsumer(oauthInfo.consumerKey, oauthInfo.consumerSecret); consumer.setTokenWithSecret(oauthToken, oauthSecret); consumer.sign(connection); } return connection; } catch(Exception e) { throw new RuntimeException(e); } }
Example 7
Source File: MainActivity.java From together-go with GNU Lesser General Public License v3.0 | 5 votes |
private void setToken() { Runnable runnable = new Runnable() { @Override public void run() { try { URL url = new URL("http://gt.buxingxing.com/api/v1/token"); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setReadTimeout(5000); conn.setConnectTimeout(5000); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.connect(); DataOutputStream out = new DataOutputStream(conn.getOutputStream()); JSONObject body = new JSONObject(); body.put("openid", openid); body.put("token", gwgo_token); String json = java.net.URLEncoder.encode(body.toString(), "utf-8"); out.writeBytes(json); out.flush(); out.close(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String lines; StringBuffer sb = new StringBuffer(""); while((lines = reader.readLine()) != null) { lines = URLDecoder.decode(lines, "utf-8"); sb.append(lines); } reader.close(); conn.disconnect(); } catch (Exception e) { e.printStackTrace(); } } }; fixedThreadPool.execute(runnable); }
Example 8
Source File: AcceptHeaderAcceptCharsetHeaderITCase.java From olingo-odata4 with Apache License 2.0 | 5 votes |
@Test public void multipleValuesInAcceptHeaderWithOneIncorrectValue() throws Exception { URL url = new URL(SERVICE_URI + "ESAllPrim"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(HttpMethod.GET.name()); connection.setRequestProperty(HttpHeader.ACCEPT, "application/json," + "application/json;q=0.1,application/json;q=0.8,abc"); connection.connect(); assertEquals(HttpStatusCode.BAD_REQUEST.getStatusCode(), connection.getResponseCode()); final String content = IOUtils.toString(connection.getErrorStream()); assertTrue(content.contains("The content-type range ' abc' is not supported as value of the Accept header.")); }
Example 9
Source File: HttpHelper.java From zxingfragmentlib with Apache License 2.0 | 5 votes |
public static URI unredirect(URI uri) throws IOException { if (!REDIRECTOR_DOMAINS.contains(uri.getHost())) { return uri; } URL url = uri.toURL(); HttpURLConnection connection = safelyOpenConnection(url); connection.setInstanceFollowRedirects(false); connection.setDoInput(false); connection.setRequestMethod("HEAD"); connection.setRequestProperty("User-Agent", "ZXing (Android)"); try { int responseCode = safelyConnect(connection); switch (responseCode) { case HttpURLConnection.HTTP_MULT_CHOICE: case HttpURLConnection.HTTP_MOVED_PERM: case HttpURLConnection.HTTP_MOVED_TEMP: case HttpURLConnection.HTTP_SEE_OTHER: case 307: // No constant for 307 Temporary Redirect ? String location = connection.getHeaderField("Location"); if (location != null) { try { return new URI(location); } catch (URISyntaxException e) { // nevermind } } } return uri; } finally { connection.disconnect(); } }
Example 10
Source File: UrlConnectionStreamFetcher.java From tinkerpatch-sdk with MIT License | 5 votes |
@Override public void run() { InputStream inputStream = null; try { HttpURLConnection conn = (HttpURLConnection) url.toURL().openConnection(); conn.setRequestMethod(url.getMethod()); conn.setDoOutput(true); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setInstanceFollowRedirects(false); conn.setUseCaches(false); for (Map.Entry<String, String> entry : url.getHeaders().entrySet()) { conn.setRequestProperty(entry.getKey(), entry.getValue()); } switch (url.getMethod()) { case "GET": break; case "POST": OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), ServerUtils.CHARSET); writer.write(url.getBody()); writer.flush(); writer.close(); break; default: throw new RuntimeException("Unsupported request method" + url.getMethod()); } conn.connect(); TinkerLog.d(TAG, "response code " + conn.getResponseCode() + " msg: " + conn.getResponseMessage()); inputStream = conn.getInputStream(); this.callback.onDataReady(inputStream); } catch (IOException e) { e.printStackTrace(); this.callback.onLoadFailed(e); } finally { SharePatchFileUtil.closeQuietly(inputStream); } }
Example 11
Source File: DownloadVideoThread.java From ripme with MIT License | 5 votes |
/** * @param url * Target URL * @return * Returns connection length */ private int getTotalBytes(URL url) throws IOException { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("HEAD"); conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("Referer", this.url.toExternalForm()); // Sic conn.setRequestProperty("User-agent", AbstractRipper.USER_AGENT); return conn.getContentLength(); }
Example 12
Source File: ODataVersionConformanceITCase.java From olingo-odata4 with Apache License 2.0 | 5 votes |
@Test public void validODataVersionAndMaxVersionHeader() throws Exception { URL url = new URL(SERVICE_URI + "ESAllPrim"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(HttpMethod.GET.name()); connection.setRequestProperty(HttpHeader.ODATA_VERSION, "4.0"); connection.setRequestProperty(HttpHeader.ODATA_MAX_VERSION, "5.0"); connection.connect(); assertEquals("4.0", connection.getHeaderField(HttpHeader.ODATA_VERSION)); final String content = IOUtils.toString(connection.getErrorStream()); assertNotNull(content);; }
Example 13
Source File: RequestExecutionHelper.java From cloud-espm-v2 with Apache License 2.0 | 5 votes |
/** * Run a http get request * * @param serviceEndPoint * @return http response * @throws IOException */ public static HttpResponse executeGetRequest(String serviceEndPoint) throws IOException { URL url = new URL(SERVICE_ROOT_URI + serviceEndPoint); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/atom+xml"); try { return new HttpResponse(connection); } finally { connection.disconnect(); } }
Example 14
Source File: KerberosWebHDFSConnection.java From Transwarp-Sample-Code with MIT License | 4 votes |
/** * curl -i -X POST * "http://<HOST>:<PORT>/webhdfs/v1/<PATH>?op=APPEND[&buffersize=<INT>]" * * @param path * @param is * @return * @throws MalformedURLException * @throws IOException * @throws AuthenticationException */ public String append(String path, InputStream is) throws MalformedURLException, IOException, AuthenticationException { String resp = null; ensureValidToken(); String redirectUrl = null; HttpURLConnection conn = authenticatedURL.openConnection( new URL(new URL(httpfsUrl), MessageFormat.format( "/webhdfs/v1/{0}?delegation="+delegation+"&op=APPEND", path)), token); conn.setRequestMethod("POST"); conn.setInstanceFollowRedirects(false); conn.connect(); logger.info("Location:" + conn.getHeaderField("Location")); resp = result(conn, true); if (conn.getResponseCode() == 307) redirectUrl = conn.getHeaderField("Location"); conn.disconnect(); if (redirectUrl != null) { conn = authenticatedURL.openConnection(new URL(redirectUrl), token); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestProperty("Content-Type", "application/octet-stream"); // conn.setRequestProperty("Transfer-Encoding", "chunked"); final int _SIZE = is.available(); conn.setRequestProperty("Content-Length", "" + _SIZE); conn.setFixedLengthStreamingMode(_SIZE); conn.connect(); OutputStream os = conn.getOutputStream(); copy(is, os); // Util.copyStream(is, os); is.close(); os.close(); resp = result(conn, true); conn.disconnect(); } return resp; }
Example 15
Source File: HomeWizzardSmartPlugInfo.java From ha-bridge with Apache License 2.0 | 4 votes |
private boolean sendAction(String request, String action) { boolean result = true; // Check login was successful if (login()) { // Post action into Cloud service try { URL url = new URL(HOMEWIZARD_API_URL + request); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); JsonObject actionJson = new JsonObject(); actionJson.addProperty("action", StringUtils.capitalize(action)); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setRequestProperty("X-Session-Token", cloudSessionId); connection.setRequestProperty("Content-Type", "application/json; charset=utf-8"); OutputStream os = connection.getOutputStream(); os.write(actionJson.toString().getBytes("UTF-8")); os.close(); BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder buffer = new StringBuilder(); String line; while((line = br.readLine()) != null) { buffer.append(line).append("\n"); } br.close(); connection.disconnect(); // Check if request was Ok if (!buffer.toString().contains("Success")) { result = false; } } catch(IOException e) { log.warn("Error while post json action: {} ", request, e); result = false; } } else { result = false; } return result; }
Example 16
Source File: StravaAuthenticator.java From JStrava with MIT License | 4 votes |
public AuthResponse getToken(String code) { if (secrete == null) { throw new IllegalStateException("Application secrete is not set"); } try { URI uri = new URI(TOKEN_URL); URL url = uri.toURL(); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); try { StringBuilder sb = new StringBuilder(); sb.append("client_id=" + clientId); sb.append("&client_secret=" + secrete); sb.append("&code=" + code); conn.setRequestMethod("POST"); conn.setRequestProperty("Accept", "application/json"); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); os.write(sb.toString().getBytes("UTF-8")); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } Reader br = new InputStreamReader((conn.getInputStream())); Gson gson = new Gson(); return gson.fromJson(br, AuthResponse.class); } finally { conn.disconnect(); } } catch (Exception e) { e.printStackTrace(); return null; } }
Example 17
Source File: DefaultGiteaConnection.java From gitea-plugin with MIT License | 4 votes |
private <T> T post(UriTemplate template, Object body, final Class<T> modelClass) throws IOException, InterruptedException { HttpURLConnection connection = openConnection(template); withAuthentication(connection); connection.setRequestMethod("POST"); byte[] bytes; if (body != null) { bytes = mapper.writer(new StdDateFormat()).writeValueAsBytes(body); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Content-Length", Integer.toString(bytes.length)); connection.setDoOutput(true); } else { bytes = null; connection.setDoOutput(false); } connection.setDoInput(!Void.class.equals(modelClass)); try { connection.connect(); if (bytes != null) { try (OutputStream os = connection.getOutputStream()) { os.write(bytes); } } int status = connection.getResponseCode(); if (status / 100 == 2) { if (Void.class.equals(modelClass)) { return null; } try (InputStream is = connection.getInputStream()) { return mapper.readerFor(modelClass).readValue(is); } } throw new GiteaHttpStatusException( status, connection.getResponseMessage(), bytes != null ? new String(bytes, StandardCharsets.UTF_8) : null ); } finally { connection.disconnect(); } }
Example 18
Source File: AgentClient.java From jxapi with Apache License 2.0 | 4 votes |
protected String issueProfilePost(String path, String data, HashMap<String, String> etag) throws java.io.IOException { URL url = new URL(this._host.getProtocol(), this._host.getHost(), this._host.getPort(), this._host.getPath()+path); HttpURLConnection conn = initializeConnection(url); conn.setRequestMethod("POST"); // Agent Profile requires either of these headers being sent // If neither are sent it will set If-None-Match to null and exception // will be caught during request if (etag.containsKey("If-Match")){ conn.addRequestProperty("If-Match", etag.get("If-Match")); } else{ conn.addRequestProperty("If-None-Match", etag.get("If-None-Match")); } conn.setRequestMethod("POST"); OutputStreamWriter writer = new OutputStreamWriter( conn.getOutputStream()); try { writer.write(data); } catch (IOException ex) { InputStream s = conn.getErrorStream(); InputStreamReader isr = new InputStreamReader(s); BufferedReader br = new BufferedReader(isr); try { String line; while((line = br.readLine()) != null){ System.out.print(line); } System.out.println(); } finally { s.close(); } throw ex; } finally { writer.close(); } try { return readFromConnection(conn); } finally { conn.disconnect(); } }
Example 19
Source File: Collect.java From o2oa with GNU Affero General Public License v3.0 | 4 votes |
public boolean validate() throws ExceptionCollectConnectError, ExceptionCollectDisable, ExceptionCollectValidateFailure, Exception { if (!Config.collect().getEnable()) { throw new ExceptionCollectDisable(); } try { URL url = new URL(this.url("/o2_collect_assemble/jaxrs/collect/validate")); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty(ConnectionAction.Access_Control_Allow_Credentials, ConnectionAction.Access_Control_Allow_Credentials_Value); connection.setRequestProperty(ConnectionAction.Access_Control_Allow_Headers, ConnectionAction.Access_Control_Allow_Headers_Value); connection.setRequestProperty(ConnectionAction.Access_Control_Allow_Methods, ConnectionAction.Access_Control_Allow_Methods_Value); connection.setRequestProperty(ConnectionAction.Cache_Control, ConnectionAction.Cache_Control_Value); connection.setRequestProperty(ConnectionAction.Content_Type, ConnectionAction.Content_Type_Value); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setDoOutput(true); connection.setDoInput(true); connection.connect(); try (OutputStream output = connection.getOutputStream()) { String req = "{\"name\":\"" + Config.collect().getName() + "\",\"password\":\"" + Config.collect().getPassword() + "\"}"; IOUtils.write(req, output, StandardCharsets.UTF_8); } if (200 != connection.getResponseCode()) { throw new ExceptionCollectValidateFailure(); } try (InputStream input = connection.getInputStream()) { byte[] buffer = IOUtils.toByteArray(input); String value = new String(buffer, DefaultCharset.name); if (!StringUtils.contains(value, "success")) { throw new ExceptionCollectValidateFailure(); } } connection.disconnect(); } catch (Exception e) { throw new ExceptionCollectConnectError(); } return true; }
Example 20
Source File: BaseRequest.java From azure-storage-android with Apache License 2.0 | 3 votes |
/** * Gets the properties. Sign with no length specified. * * @param uri * The Uri to query. * @param timeout * The timeout. * @param builder * The builder. * @param opContext * an object used to track the execution of the operation * @return a web request for performing the operation. * @throws StorageException * @throws URISyntaxException * @throws IOException * */ public static HttpURLConnection getProperties(final URI uri, final RequestOptions options, UriQueryBuilder builder, final OperationContext opContext) throws IOException, URISyntaxException, StorageException { if (builder == null) { builder = new UriQueryBuilder(); } final HttpURLConnection retConnection = createURLConnection(uri, options, builder, opContext); retConnection.setRequestMethod(Constants.HTTP_HEAD); return retConnection; }