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 } }
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; } }
HttpURLConnection httpConn = (HttpURLConnection)_urlConnection; InputStream _is; if (httpConn.getResponseCode() < 400) { _is = httpConn.getInputStream(); } else { /* error from server */ _is = httpConn.getErrorStream(); }
HttpURLConnection con = (HttpURLConnection)(new URL( url ).openConnection()); con.setInstanceFollowRedirects( false ); con.connect(); int responseCode = con.getResponseCode(); System.out.println( responseCode ); String location = con.getHeaderField( "Location" ); System.out.println( location );
/** * @param url Url. * @return Contents. * @throws IOException If failed. */ private String getHttpContents(URL url) throws IOException { HttpURLConnection conn = (HttpURLConnection)url.openConnection(); int code = conn.getResponseCode(); if (code != 200) throw null; BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); return rd.lines().collect(Collectors.joining()); }
String suggestedPluginUrl = updateCenterJsonUrl.replace("/update-center.json", "/platform-plugins.json"); try { URLConnection connection = ProxyConfiguration.open(new URL(suggestedPluginUrl)); int responseCode = ((HttpURLConnection)connection).getResponseCode(); if(HttpURLConnection.HTTP_OK != responseCode) { throw new HttpRetryException("Invalid response code (" + responseCode + ") from URL: " + suggestedPluginUrl, responseCode); String initialPluginJson = IOUtils.toString(connection.getInputStream(), "utf-8"); initialPluginList = JSONArray.fromObject(initialPluginJson); break updateSiteList;
@RequirePOST public FormValidation doCheckUrl(@QueryParameter String value) { Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER); try { URLConnection conn = ProxyConfiguration.open(new URL(value)); conn.connect(); if (conn instanceof HttpURLConnection) { if (((HttpURLConnection) conn).getResponseCode() != HttpURLConnection.HTTP_OK) { return FormValidation.error(Messages.ZipExtractionInstaller_bad_connection()); } } return FormValidation.ok(); } catch (MalformedURLException x) { return FormValidation.error(Messages.ZipExtractionInstaller_malformed_url()); } catch (IOException x) { return FormValidation.error(x,Messages.ZipExtractionInstaller_could_not_connect()); } }
URL findResource(String name) { URL resURL = targetURL(url, name); if (resURL != null) { try { URLConnection uc = resURL.openConnection(); uc.getInputStream().close(); // HTTP can return a stream on a non-existent file // So check for the return code; if (!resURL.getProtocol().equals("http")) { return resURL; } int code; if ((code = ((HttpURLConnection) uc).getResponseCode()) >= 200 && code < 300) { return resURL; } } catch (SecurityException e) { return null; } catch (IOException e) { return null; } } 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); } }
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
public static int getHttpCode() throws IOException { return ((HttpURLConnection) new URL("http://localhost:8080") .openConnection()).getResponseCode(); }
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; } }
@Before public void setUp() throws IOException { MockitoAnnotations.initMocks(this); URL url = new URL("http://www.google.com"); when(connectionFactory.build(eq(url))).thenReturn(urlConnection); when(urlConnection.getInputStream()).thenReturn(stream); when(urlConnection.getResponseCode()).thenReturn(200); when(glideUrl.toURL()).thenReturn(url); fetcher = new HttpUrlFetcher(glideUrl, TIMEOUT_MS, connectionFactory); }
@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); } }
HttpURLConnection httpConn = (HttpURLConnection)connection; InputStream is; if (httpConn.getResponseCode() >= 400) { is = httpConn.getErrorStream(); } else { is = httpConn.getInputStream(); }
URL url = new URL("http://example.com"); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); int code = connection.getResponseCode();
private int getHttpCode() throws IOException { return ((HttpURLConnection) new URL("http://localhost:8080") .openConnection()).getResponseCode(); }
/** * @param metaDataKey The metadata key * @param url The URL * @param connectionTimeoutMs The connection timeout * @param readTimeoutMs The read timeout in milliseconds * @return The metadata * @throws IOException if there is an error */ @SuppressWarnings("EmptyBlock") static String readEc2MetadataUrl(AmazonInfo.MetaDataKey metaDataKey, URL url, int connectionTimeoutMs, int readTimeoutMs) throws IOException { HttpURLConnection uc = (HttpURLConnection) url.openConnection(); uc.setConnectTimeout(connectionTimeoutMs); uc.setReadTimeout(readTimeoutMs); if (uc.getResponseCode() != HttpURLConnection.HTTP_OK) { // need to read the error for clean connection close try (BufferedReader br = new BufferedReader(new InputStreamReader(uc.getErrorStream()))) { while (br.readLine() != null) { // do nothing but keep reading the line } } } else { return metaDataKey.read(uc.getInputStream()); } return null; }
URLConnection connection = url.openConnection(); InputStream is = connection.getInputStream(); if (connection instanceof HttpURLConnection) { HttpURLConnection httpConn = (HttpURLConnection) connection; int statusCode = httpConn.getResponseCode(); if (statusCode != 200 /* or statusCode >= 200 && statusCode < 300 */) { is = httpConn.getErrorStream(); } }
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(); input = connection.getInputStream(); output = new FileOutputStream("/sdcard/file_name.extension");