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 } }
HttpURLConnection httpConnection = (HttpURLConnection) new URL(url).openConnection(); httpConnection.setRequestMethod("POST"); // ...
private static <T> T get(String url, Type type) throws IOException { URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); if (con.getResponseCode() == 200) { Reader reader = new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8); return GSON.fromJson(reader, type); } return null; } }
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); } }
private int tryGetFileSize(URL url) { HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("HEAD"); conn.getInputStream(); return conn.getContentLength(); } catch (IOException e) { return -1; } finally { conn.disconnect(); } }
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); FileBody fileBody = new FileBody(new File(fileName)); MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT); multipartEntity.addPart("file", fileBody); connection.setRequestProperty("Content-Type", multipartEntity.getContentType().getValue()); OutputStream out = connection.getOutputStream(); try { multipartEntity.writeTo(out); } finally { out.close(); } int status = connection.getResponseCode(); ...
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod("HEAD"); int responseCode = connection.getResponseCode(); if (responseCode != 200) { // Not OK. } // < 100 is undetermined. // 1nn is informal (shouldn't happen on a GET/HEAD) // 2nn is success // 3nn is redirect // 4nn is client error // 5nn is server error
private static HttpURLConnection makePreSignedRequest(String method, String preSignedUrl, Map headers) throws IOException { URL url = new URL(preSignedUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(method); addHeaders(connection, headers); return connection; }
private FileInformation readFileInformation(URL url) { FileInformation fileInformation = new FileInformation(); URLConnection urlConnection; try { if (url.getProtocol().startsWith("http")) { urlConnection = url.openConnection(); ((HttpURLConnection) urlConnection).setRequestMethod("HEAD"); try (InputStream inputStream = urlConnection.getInputStream()) { fileInformation.length = urlConnection.getContentLength(); fileInformation.lastModified = urlConnection.getLastModified(); } } else { if (url.getProtocol().startsWith("file")) { File file = new File(url.getFile()); if (file.exists()) { fileInformation = new FileInformation(file); } } } } catch (IOException e) { if (LOG.isLoggable(Level.WARNING)) LOG.log(Level.WARNING, "Failed to obtain age and length of URL " + url, e); } return fileInformation; }
@Override public void handleDataPoints(TaskInfo taskInfo, Collection<DataPoint> dataPoints) { try { HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("POST"); con.setDoOutput(true); try (Output out = new Output(con.getOutputStream())) { serializer.serializeInto(Arrays.asList(taskInfo, dataPoints, topologyId), out); out.flush(); } //The connection is not sent unless a response is requested int response = con.getResponseCode(); } catch (Exception e) { throw new RuntimeException(e); } }
URL url = new URL("http://www.example.com/resource"); HttpURLConnection httpCon = (HttpURLConnection) url.openConnection(); httpCon.setDoOutput(true); httpCon.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded" ); httpCon.setRequestMethod("DELETE"); httpCon.connect();
@Test public void testBindOnHost() throws Exception { Assert.assertEquals("localhost", server.getURI().getHost()); final URL url = new URL("http://localhost:" + port + "/default"); final HttpURLConnection get = (HttpURLConnection) url.openConnection(); Assert.assertEquals(DEFAULT_RESPONSE_CONTENT, IOUtils.toString(get.getInputStream(), StandardCharsets.UTF_8)); final HttpURLConnection post = (HttpURLConnection) url.openConnection(); post.setRequestMethod("POST"); Assert.assertEquals(DEFAULT_RESPONSE_CONTENT, IOUtils.toString(post.getInputStream(), StandardCharsets.UTF_8)); } }
URL url = new URL("http://www.example.com/resource"); HttpURLConnection httpCon = (HttpURLConnection) url.openConnection(); httpCon.setDoOutput(true); httpCon.setRequestMethod("PUT"); OutputStreamWriter out = new OutputStreamWriter( httpCon.getOutputStream()); out.write("Resource content"); out.close(); httpCon.getInputStream();
@Test public void testProxyGzipCompression() throws Exception { final URL url = new URL("http://localhost:" + port + "/proxy/default"); final HttpURLConnection get = (HttpURLConnection) url.openConnection(); get.setRequestProperty("Accept-Encoding", "gzip"); Assert.assertEquals("gzip", get.getContentEncoding()); final HttpURLConnection post = (HttpURLConnection) url.openConnection(); post.setRequestProperty("Accept-Encoding", "gzip"); post.setRequestMethod("POST"); Assert.assertEquals("gzip", post.getContentEncoding()); final HttpURLConnection getNoGzip = (HttpURLConnection) url.openConnection(); Assert.assertNotEquals("gzip", getNoGzip.getContentEncoding()); final HttpURLConnection postNoGzip = (HttpURLConnection) url.openConnection(); postNoGzip.setRequestMethod("POST"); Assert.assertNotEquals("gzip", postNoGzip.getContentEncoding()); }
HttpURLConnection httpUrlConnection = null; URL url = new URL("http://example.com/server.cgi"); httpUrlConnection = (HttpURLConnection) url.openConnection(); httpUrlConnection.setUseCaches(false); httpUrlConnection.setDoOutput(true); httpUrlConnection.setRequestMethod("POST"); httpUrlConnection.setRequestProperty("Connection", "Keep-Alive"); httpUrlConnection.setRequestProperty("Cache-Control", "no-cache"); httpUrlConnection.setRequestProperty( "Content-Type", "multipart/form-data;boundary=" + this.boundary);
URL url = new URL("http://example.com"); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); int code = connection.getResponseCode();
URL myURL = new URL(serviceURL); HttpURLConnection myURLConnection = (HttpURLConnection)myURL.openConnection(); String userCredentials = "username:password"; String basicAuth = "Basic " + new String(new Base64().encode(userCredentials.getBytes())); myURLConnection.setRequestProperty ("Authorization", basicAuth); myURLConnection.setRequestMethod("POST"); myURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); myURLConnection.setRequestProperty("Content-Length", "" + postData.getBytes().length); myURLConnection.setRequestProperty("Content-Language", "en-US"); myURLConnection.setUseCaches(false); myURLConnection.setDoInput(true); myURLConnection.setDoOutput(true);
String urlParameters = "param1=a¶m2=b¶m3=c"; byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 ); int postDataLength = postData.length; String request = "http://example.com/index.php"; URL url = new URL( request ); HttpURLConnection conn= (HttpURLConnection) url.openConnection(); conn.setDoOutput( true ); conn.setInstanceFollowRedirects( false ); conn.setRequestMethod( "POST" ); conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty( "charset", "utf-8"); conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength )); conn.setUseCaches( false ); try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream())) { wr.write( postData ); }
String rawData = "id=10"; String type = "application/x-www-form-urlencoded"; String encodedData = URLEncoder.encode( rawData ); URL u = new URL("http://www.example.com/page.php"); HttpURLConnection conn = (HttpURLConnection) u.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty( "Content-Type", type ); conn.setRequestProperty( "Content-Length", String.valueOf(encodedData.length())); OutputStream os = conn.getOutputStream(); os.write(encodedData.getBytes());
URL url = new URL("http://www.example.com/login"); URLConnection con = url.openConnection(); HttpURLConnection http = (HttpURLConnection)con; http.setRequestMethod("POST"); // PUT is another valid option http.setDoOutput(true);