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(); }
/** * Template method for preparing the given {@link HttpURLConnection}. * <p>The default implementation prepares the connection for input and output, and sets the HTTP method. * @param connection the connection to prepare * @param httpMethod the HTTP request method ({@code GET}, {@code POST}, etc.) * @throws IOException in case of I/O errors */ protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException { if (this.connectTimeout >= 0) { connection.setConnectTimeout(this.connectTimeout); } if (this.readTimeout >= 0) { connection.setReadTimeout(this.readTimeout); } connection.setDoInput(true); if ("GET".equals(httpMethod)) { connection.setInstanceFollowRedirects(true); } else { connection.setInstanceFollowRedirects(false); } if ("POST".equals(httpMethod) || "PUT".equals(httpMethod) || "PATCH".equals(httpMethod) || "DELETE".equals(httpMethod)) { connection.setDoOutput(true); } else { connection.setDoOutput(false); } connection.setRequestMethod(httpMethod); }
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); }
/** Downloads the content of the specified url to the array. The array has to be big enough. */ private int download (byte[] out, String url) { InputStream in = null; try { HttpURLConnection conn = null; conn = (HttpURLConnection)new URL(url).openConnection(); conn.setDoInput(true); conn.setDoOutput(false); conn.setUseCaches(true); conn.connect(); in = conn.getInputStream(); int readBytes = 0; while (true) { int length = in.read(out, readBytes, out.length - readBytes); if (length == -1) break; readBytes += length; } return readBytes; } catch (Exception ex) { return 0; } finally { StreamUtils.closeQuietly(in); } }
String auth = new URL(home).getUserInfo(); if(auth != null) auth = "Basic " + new Base64Encoder().encode(auth.getBytes("UTF-8")); HttpURLConnection con = open(new URL(home)); if (auth != null) con.setRequestProperty("Authorization", auth); con.connect(); if(con.getResponseCode()!=200 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) { 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(":"); con.setRequestProperty(crumbField, crumbValue); con.setDoOutput(true); org.apache.commons.io.IOUtils.copy(in, con.getOutputStream()); } catch (InvalidPathException e) { throw new IOException(e);
public HttpURLConnection connectToEndpoint(URI endpoint, Map<String, String> headers) throws IOException { HttpURLConnection connection = (HttpURLConnection) endpoint.toURL().openConnection(Proxy.NO_PROXY); connection.setConnectTimeout(1000 * 2); connection.setReadTimeout(1000 * 5); connection.setRequestMethod("GET"); connection.setDoOutput(true); for (Map.Entry<String, String> header : headers.entrySet()) { connection.addRequestProperty(header.getKey(), header.getValue()); } // TODO should we autoredirect 3xx // connection.setInstanceFollowRedirects(false); connection.connect(); return connection; }
private InputStream readData(int offset, int length) throws IOException{ HttpURLConnection conn = (HttpURLConnection) zipUrl.openConnection(); conn.setDoOutput(false); conn.setUseCaches(false); conn.setInstanceFollowRedirects(false); String range = "-"; if (offset != Integer.MAX_VALUE){ range = offset + range; } if (length != Integer.MAX_VALUE){ if (offset != Integer.MAX_VALUE){ range = range + (offset + length - 1); }else{ range = range + length; } } conn.setRequestProperty("Range", "bytes=" + range); conn.connect(); if (conn.getResponseCode() == HttpURLConnection.HTTP_PARTIAL){ return conn.getInputStream(); }else if (conn.getResponseCode() == HttpURLConnection.HTTP_OK){ throw new IOException("Your server does not support HTTP feature Content-Range. Please contact your server administrator."); }else{ throw new IOException(conn.getResponseCode() + " " + conn.getResponseMessage()); } }
private static void addBodyIfExists(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { byte[] body = request.getBody(); if (body != null) { connection.setDoOutput(true); connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(body); out.close(); } } }
public void post(ByteArrayOutputStream payload) throws IOException { final HttpURLConnection connection = (HttpURLConnection) openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); if (payload != null) { final OutputStream outputStream = connection.getOutputStream(); payload.writeTo(outputStream); outputStream.flush(); } final int status = connection.getResponseCode(); if (status >= HttpURLConnection.HTTP_BAD_REQUEST) { final String error = InputOutput.pumpToString(connection.getErrorStream(), Charset.forName("UTF-8")); final String msg = "Error connecting to " + url + '(' + status + "): " + error; throw new IOException(msg); } connection.disconnect(); }
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();
/** * 设置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);
private static void addBodyIfExists(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { byte[] body = request.getBody(); if (body != null) { connection.setDoOutput(true); connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(body); out.close(); } } }
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());
@NonNull private HttpResponse getHttpResponseResult(final @NonNull HttpRequest request, @NonNull final HttpURLConnection connection) throws IOException { connection.setConnectTimeout(request.connectTimeoutMs); connection.setReadTimeout(request.readTimeoutMs); connection.setInstanceFollowRedirects(request.followRedirects); connection.setUseCaches(request.useCaches); connection.setDoInput(true); connection.setRequestMethod(request.method); for (final Entry<String, String> headerField : request.header.entrySet()) { connection.addRequestProperty(headerField.getKey(), headerField.getValue()); } final byte[] body = request.body; if (body.length > 0) { connection.setDoOutput(true); final OutputStream out = connection.getOutputStream(); try { out.write(body); } finally { out.close(); } } final String responseMessage = connection.getResponseMessage(); return httpResponse(connection.getResponseCode(), responseMessage != null ? responseMessage : "", getHeader(connection), getByteArray(connection)); }
@NotNull private HttpURLConnection postToServer(String json, URL url) throws IOException { HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestMethod("POST"); conn.setUseCaches(false); conn.setRequestProperty("Content-Type", "application/json"); conn.setDoOutput(true); try { try (DataOutputStream dos = new DataOutputStream(conn.getOutputStream())) { //System.out.println("POSTING: " + json); dos.write(json.getBytes("utf-8")); } } catch (IOException e) { throw new RuntimeException("Could not connect OpenNMT server at " + url); } return conn; }
private static void addBodyIfExists(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { byte[] body = request.getBody(); if (body != null) { connection.setDoOutput(true); connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(body); out.close(); } } }
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());