canonical example by Tabnine
public void postRequest(String urlStr, String jsonBodyStr) throws IOException { URL url = new URL(urlStr); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setDoOutput(true); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setRequestProperty("Content-Type", "application/json"); try (OutputStream outputStream = httpURLConnection.getOutputStream()) { outputStream.write(jsonBodyStr.getBytes()); outputStream.flush(); } if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) { try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()))) { String line; while ((line = bufferedReader.readLine()) != null) { // ... do something with line } } } else { // ... do something with unsuccessful response } }
/** * Helper method to make an HTTP request. * @param urlConnection The HTTP connection. */ public void writeToUrlConnection(HttpURLConnection urlConnection) throws IOException { urlConnection.setDoOutput(true); urlConnection.setRequestProperty("Content-Type", "application/json"); urlConnection.setRequestProperty("Accept", "application/json"); urlConnection.setRequestMethod("POST"); OutputStream os = urlConnection.getOutputStream(); os.write(mJsonObject.toString().getBytes("UTF-8")); os.close(); }
public void configure(HttpURLConnection httpURLConnection) throws ProtocolException { httpURLConnection.setRequestMethod(requestMethod); httpURLConnection.setDoInput(true); httpURLConnection.setDoOutput(true); httpURLConnection.setReadTimeout(readTimeoutInMillis); if (contentType != null) httpURLConnection.setRequestProperty("Content-Type", contentType); if (authorization != null) httpURLConnection.setRequestProperty("Authorization", authorization); httpURLConnection.setRequestProperty("User-Agent", userAgent); }
/** * @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(); }
HttpURLConnection con = open(new URL(home)); if (auth != null) con.setRequestProperty("Authorization", auth); con.connect(); if(con.getResponseCode()!=200 || con.getHeaderField("X-Hudson")==null) { System.err.println(home+" is not Hudson ("+con.getResponseMessage()+")"); URL jobURL = new URL(home + "job/" + Util.encode(projectName).replace("/", "/job/") + "/"); HttpURLConnection con = open(new URL(jobURL, "acceptBuildResult")); if (auth != null) con.setRequestProperty("Authorization", auth); con.connect(); if(con.getResponseCode()!=200) { System.err.println(jobURL + " is not a valid external job (" + con.getResponseCode() + " " + con.getResponseMessage() + ")"); return -1; HttpURLConnection con = open(new URL(home + "crumbIssuer/api/xml?xpath=concat(//crumbRequestField,\":\",//crumb)'")); if (auth != null) con.setRequestProperty("Authorization", auth); String line = IOUtils.readFirstLine(con.getInputStream(),"UTF-8"); String[] components = line.split(":"); if (components.length == 2) { if (auth != null) con.setRequestProperty("Authorization", auth); if (crumbField != null && crumbValue != null) { con.setRequestProperty(crumbField, crumbValue); con.setDoOutput(true);
public HttpURLConnection createConnection(String urlStr) throws IOException { URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // Will yield in a POST request: conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(true); conn.setRequestProperty("Referrer", referrer); conn.setRequestProperty("User-Agent", userAgent); // suggest respond to be gzipped or deflated (which is just another compression) // http://stackoverflow.com/q/3932117 conn.setRequestProperty("Accept-Encoding", acceptEncoding); conn.setReadTimeout(timeout); conn.setConnectTimeout(timeout); return conn; }
public void request(String urlString) { HttpURLConnection urlConnection = null; try { URL url = new URL(urlString); urlConnection = openURLConnection(url); urlConnection.setInstanceFollowRedirects(true); urlConnection.setRequestMethod(GET_METHOD_NAME); urlConnection.setRequestProperty("User-agent", uaName + " (" + osString + ")"); logger.debug("Sending Server's information to Atmosphere's Google Analytics {} {}", urlString, uaName + " (" + osString + ")"); urlConnection.connect(); int responseCode = getResponseCode(urlConnection); if (responseCode != HttpURLConnection.HTTP_OK) { logError("JGoogleAnalytics: Error tracking, url=" + urlString); } else { logMessage(SUCCESS_MESSAGE); } } catch (Exception e) { logError(e.getMessage()); } finally { if (urlConnection != null) { urlConnection.disconnect(); } } }
private HttpURLConnection create(URL url) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Accept", "application/*"); connection.setConnectTimeout(10000); return connection; }
routingType, "POST"); conn.setDoOutput(true); if(vectorClock != null) { conn.setRequestProperty(RestMessageHeaders.X_VOLD_VECTOR_CLOCK, vectorClock); conn.setRequestProperty("Content-Type", ContentType); conn.setRequestProperty("Content-Length", contentLength); OutputStream out = conn.getOutputStream(); out.write(value.getBytes()); out.close();
@Override protected URLConnection openConnection(URL url, Proxy proxy) throws IOException { HttpURLConnection connection = (HttpURLConnection) super.openConnection(url, proxy); connection.setRequestMethod(this.httpMethod); if (resourceDetails.isAcceptsAuthorizationHeader()) { String authHeader = support.getAuthorizationHeader(resourceDetails, accessToken, url, httpMethod, additionalParameters); connection.setRequestProperty("Authorization", authHeader); } return connection; }
/** * 设置http请求默认属性 * * @param httpConnection */ protected void setHttpRequest(HttpURLConnection httpConnection) { //设置连接超时时间 httpConnection.setConnectTimeout(this.timeOut * 1000); //User-Agent httpConnection.setRequestProperty("User-Agent", HttpClient.USER_AGENT_VALUE); //不使用缓存 httpConnection.setUseCaches(false); //允许输入输出 httpConnection.setDoInput(true); httpConnection.setDoOutput(true); }
private HttpURLConnection post(final String path, final byte[] body) throws IOException { final URL url = new URL(masterEndpoint() + path); final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setDoInput(true); connection.setDoOutput(true); connection.getOutputStream().write(body); return connection; } }
URL url = new URL(ENDPOINT); URLConnection conn = ProxyConfiguration.open(url); if (!(conn instanceof HttpURLConnection)) { http.setRequestProperty("Content-Type", "application/json; charset=utf-8"); http.setDoOutput(true); try (OutputStream out = http.getOutputStream(); OutputStreamWriter writer = new OutputStreamWriter(out, StandardCharsets.UTF_8)) { writer.append(body); LOGGER.config("Telemetry submission received response '" + http.getResponseCode() + " " + http.getResponseMessage() + "' for: " + telemetry.getId()); } catch (MalformedURLException e) { LOGGER.config("Malformed endpoint URL: " + ENDPOINT + " for telemetry: " + telemetry.getId());
/** * Open connection * * @param threadId id of the calling thread, used only for debug * @param rangeStart range start * @param rangeEnd range end * @return a {@link java.net.URLConnection URLConnection} linking to the URL. * @throws IOException if an I/O exception occurs. */ HttpURLConnection openConnection(int threadId, long rangeStart, long rangeEnd) throws IOException { URL url = new URL(urls[current]); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setInstanceFollowRedirects(true); if (rangeStart >= 0) { String req = "bytes=" + rangeStart + "-"; if (rangeEnd > 0) req += rangeEnd; conn.setRequestProperty("Range", req); if (DEBUG) { Log.d(TAG, threadId + ":" + conn.getRequestProperty("Range")); } } return conn; }
private static HttpURLConnection createConnection(URL url) throws IOException { HttpURLConnection connection; connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty(USER_AGENT_HEADER, getUserAgent()); connection.setRequestProperty(ACCEPT_LANGUAGE_HEADER, Locale.getDefault().toString()); connection.setChunkedStreamingMode(0); return connection; }
connection.setDoOutput(true); connection.setRequestMethod(HTTP_METHOD_POST); connection.setRequestProperty(HTTP_HEADER_CONTENT_TYPE, getContentType()); connection.setRequestProperty(HTTP_HEADER_CONTENT_LENGTH, Integer.toString(contentLength)); Locale locale = localeContext.getLocale(); if (locale != null) { connection.setRequestProperty(HTTP_HEADER_ACCEPT_LANGUAGE, locale.toLanguageTag()); connection.setRequestProperty(HTTP_HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
@Override protected URLConnection openConnection(URL url, Proxy proxy) throws IOException { HttpURLConnection connection = (HttpURLConnection) super.openConnection(url, proxy); connection.setRequestMethod(this.httpMethod); if (resourceDetails.isAcceptsAuthorizationHeader()) { String authHeader = support.getAuthorizationHeader(resourceDetails, accessToken, url, httpMethod, additionalParameters); connection.setRequestProperty("Authorization", authHeader); } return connection; }
public boolean checkStatus(URL serverURL) { try { // 1. Set up the connection HttpURLConnection connection = (HttpURLConnection) serverURL.openConnection(); // 1.1 Set authentication if (apiKey != null && apiSecret != null) { String userpass = apiKey + ':' + apiSecret; String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes())); connection.setRequestProperty("Authorization", basicAuth); } connection.setRequestMethod("GET"); connection.connect(); return connection.getResponseCode() >= 200 && connection.getResponseCode() <= 400; } catch (Throwable t) { throw new RuntimeException(t); } }
connection.setDoOutput(true); connection.setRequestMethod(HTTP_METHOD_POST); connection.setRequestProperty(HTTP_HEADER_CONTENT_TYPE, getContentType()); connection.setRequestProperty(HTTP_HEADER_CONTENT_LENGTH, Integer.toString(contentLength)); Locale locale = localeContext.getLocale(); if (locale != null) { connection.setRequestProperty(HTTP_HEADER_ACCEPT_LANGUAGE, locale.toLanguageTag()); connection.setRequestProperty(HTTP_HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
public void callCouchbaseRestAPI(String url, String payload) throws IOException { String fullUrl = urlBase + url; @Cleanup("disconnect") HttpURLConnection httpConnection = (HttpURLConnection) ((new URL(fullUrl).openConnection())); httpConnection.setDoOutput(true); httpConnection.setRequestMethod("POST"); httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); String encoded = Base64.encode((clusterUsername + ":" + clusterPassword).getBytes("UTF-8")); httpConnection.setRequestProperty("Authorization", "Basic " + encoded); @Cleanup DataOutputStream out = new DataOutputStream(httpConnection.getOutputStream()); out.writeBytes(payload); out.flush(); httpConnection.getResponseCode(); }