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 } }
public static String readEc2MetadataUrl(MetaDataKey metaDataKey, URL url, int connectionTimeoutMs, int readTimeoutMs) throws IOException { HttpURLConnection uc = (HttpURLConnection) url.openConnection(); uc.setConnectTimeout(connectionTimeoutMs); uc.setReadTimeout(readTimeoutMs); uc.setRequestProperty("User-Agent", "eureka-java-client"); if (uc.getResponseCode() != HttpURLConnection.HTTP_OK) { // need to read the error for clean connection close BufferedReader br = new BufferedReader(new InputStreamReader(uc.getErrorStream())); try { while (br.readLine() != null) { // do nothing but keep reading the line } } finally { br.close(); } } else { return metaDataKey.read(uc.getInputStream()); } return null; } }
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; } }
/** 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); } }
@Override public InputStream getBody() throws IOException { InputStream errorStream = this.connection.getErrorStream(); this.responseStream = (errorStream != null ? errorStream : this.connection.getInputStream()); return this.responseStream; }
/** * Connects to the given HTTP URL and configure time out, to avoid infinite hang. */ private static HttpURLConnection open(URL url) throws IOException { HttpURLConnection c = (HttpURLConnection)url.openConnection(); c.setReadTimeout(TIMEOUT); c.setConnectTimeout(TIMEOUT); return c; }
/** * Validate the given response as contained in the {@link HttpURLConnection} object, * throwing an exception if it does not correspond to a successful HTTP response. * <p>Default implementation rejects any HTTP status code beyond 2xx, to avoid * parsing the response body and trying to deserialize from a corrupted stream. * @param config the HTTP invoker configuration that specifies the target service * @param con the HttpURLConnection to validate * @throws IOException if validation failed * @see java.net.HttpURLConnection#getResponseCode() */ protected void validateResponse(HttpInvokerClientConfiguration config, HttpURLConnection con) throws IOException { if (con.getResponseCode() >= 300) { throw new IOException( "Did not receive successful HTTP response: status code = " + con.getResponseCode() + ", status message = [" + con.getResponseMessage() + "]"); } }
String response = ""; try { url = new URL(requestURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(15000); conn.setConnectTimeout(15000); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); os.close(); int responseCode=conn.getResponseCode(); BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line=br.readLine()) != null) { response+=line;
URL url = new URL(targetURL); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length)); connection.setRequestProperty("Content-Language", "en-US"); connection.setUseCaches(false); InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); StringBuilder response = new StringBuilder(); // or StringBuffer if Java version 5+ String line; while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); rd.close(); return response.toString(); } catch (Exception e) { } finally { if (connection != null) { connection.disconnect();
HttpURLConnection c = null; try { URL u = new URL(url); c = (HttpURLConnection) u.openConnection(); c.setRequestMethod("GET"); c.setRequestProperty("Content-length", "0"); c.setUseCaches(false); c.setAllowUserInteraction(false); c.setConnectTimeout(timeout); c.setReadTimeout(timeout); c.connect(); int status = c.getResponseCode(); BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line+"\n"); br.close(); return sb.toString(); if (c != null) { try { c.disconnect(); } catch (Exception ex) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
protected final String sendPostRequest(String request) throws IOException { URL url = new URL("http", DEFAULT_HOST, this.port, request); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("POST"); con.setDoOutput(true); OutputStream out = con.getOutputStream(); out.write("".getBytes()); out.flush(); InputStream in = con.getInputStream(); String response = CharStreams.toString(new InputStreamReader(con.getInputStream())); in.close(); return response; }
HttpURLConnection connection = null; try { URL url = new URL(sUrl[0]); connection = (HttpURLConnection) url.openConnection(); connection.connect(); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { return "Server returned HTTP " + connection.getResponseCode() + " " + connection.getResponseMessage(); int fileLength = connection.getContentLength(); input = connection.getInputStream(); output = new FileOutputStream("/sdcard/file_name.extension"); long total = 0; int count; while ((count = input.read(data)) != -1) { input.close(); return null; output.write(data, 0, count); connection.disconnect();
import java.io.*; import java.net.*; public class c { public static String getHTML(String urlToRead) throws Exception { StringBuilder result = new StringBuilder(); URL url = new URL(urlToRead); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { result.append(line); } rd.close(); return result.toString(); } public static void main(String[] args) throws Exception { System.out.println(getHTML(args[0])); } }
private boolean updateIndexConfig(String tableName, TableConfig tableConfig) throws Exception { String request = ControllerRequestURLBuilder.baseUrl("http://" + _controllerAddress).forTableUpdateIndexingConfigs(tableName); HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(request).openConnection(); httpURLConnection.setDoOutput(true); httpURLConnection.setRequestMethod("PUT"); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(httpURLConnection.getOutputStream(), "UTF-8")); writer.write(tableConfig.toJSONConfigString()); writer.flush(); BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8")); return reader.readLine().equals("done"); }
connection.setRequestMethod("GET"); connection.connect(); if (connection.getErrorStream() != null || connection.getResponseCode() != HttpURLConnection.HTTP_OK) { BufferedReader r = new BufferedReader(new InputStreamReader(connection.getErrorStream())); StringBuilder error = new StringBuilder(); String line; while ((line = r.readLine()) != null) { error.append(line).append('\n'); connection.getResponseCode() + "\n" + error)); FileExtension extension; LottieResult<LottieComposition> result; switch (connection.getContentType()) { case "application/zip": L.debug("Handling zip response."); extension = FileExtension.Zip; file = networkCache.writeTempCacheFile(connection.getInputStream(), extension); result = LottieCompositionFactory.fromZipStreamSync(new ZipInputStream(new FileInputStream(file)), url); break; L.debug("Received json response."); extension = FileExtension.Json; file = networkCache.writeTempCacheFile(connection.getInputStream(), extension); result = LottieCompositionFactory.fromJsonInputStreamSync(new FileInputStream(new File(file.getAbsolutePath())), url); break;
URL url = new URL("http","www.google.com"); HttpURLConnection urlc = (HttpURLConnection)url.openConnection(); urlc.setAllowUserInteraction( false ); urlc.setDoInput( true ); urlc.setDoOutput( false ); urlc.setUseCaches( true ); urlc.setRequestMethod("GET"); urlc.connect(); // check you have received an status code 200 to indicate OK // get the encoding from the Content-Type header BufferedReader in = new BufferedReader(new InputStreamReader(urlc.getInputStream())); String line = null; while((line = in.readLine()) != null) { System.out.println(line); } // close sockets, handle errors, etc.
URL url = new URL ("http://ip:port/login"); String encoding = Base64Encoder.encode ("test1:test1"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setRequestProperty ("Authorization", "Basic " + encoding); InputStream content = (InputStream)connection.getInputStream(); BufferedReader in = new BufferedReader (new InputStreamReader (content)); String line; while ((line = in.readLine()) != null) { System.out.println(line);
public static JsonObject getContent() throws IOException { URL url = new URL("http://localhost:8080"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); InputStreamReader in = new InputStreamReader((InputStream) conn.getContent()); BufferedReader buff = new BufferedReader(in); String line; StringBuilder builder = new StringBuilder(); do { line = buff.readLine(); builder.append(line).append("\n"); } while (line != null); buff.close(); return new JsonObject(builder.toString()); }
private StringBuffer request(String urlString) { // TODO Auto-generated method stub StringBuffer chaine = new StringBuffer(""); try{ URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setRequestProperty("User-Agent", ""); connection.setRequestMethod("POST"); connection.setDoInput(true); connection.connect(); InputStream inputStream = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream)); String line = ""; while ((line = rd.readLine()) != null) { chaine.append(line); } } catch (IOException e) { // Writing exception to log e.printStackTrace(); } return chaine; }
URL url = new URL("http://example.net/new-message.php"); Map<String,Object> params = new LinkedHashMap<>(); params.put("name", "Freddie the Fish"); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length)); conn.setDoOutput(true); conn.getOutputStream().write(postDataBytes); Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));