Tabnine Logo
HttpURLConnection.getInputStream
Code IndexAdd Tabnine to your IDE (free)

How to use
getInputStream
method
in
java.net.HttpURLConnection

Best Java code snippets using java.net.HttpURLConnection.getInputStream (Showing top 20 results out of 18,414)

Refine searchRefine arrow

  • HttpURLConnection.getResponseCode
  • URL.openConnection
  • URL.<init>
  • HttpURLConnection.setRequestMethod
  • HttpURLConnection.setRequestProperty
  • HttpURLConnection.setDoOutput
  • InputStreamReader.<init>
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
  }
}
origin: skylot/jadx

  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;
  }
}
origin: jenkinsci/jenkins

private URL tryToResolveRedirects(URL base, String authorization) {
  try {
    HttpURLConnection con = (HttpURLConnection) base.openConnection();
    if (authorization != null) {
      con.addRequestProperty("Authorization", authorization);
    }
    con.getInputStream().close();
    base = con.getURL();
  } catch (Exception ex) {
    // Do not obscure the problem propagating the exception. If the problem is real it will manifest during the
    // actual exchange so will be reported properly there. If it is not real (no permission in UI but sufficient
    // for CLI connection using one of its mechanisms), there is no reason to bother user about it.
    LOGGER.log(Level.FINE, "Failed to resolve potential redirects", ex);
  }
  return base;
}
origin: google/data-transfer-project

 private InputStream getImageAsStream(String urlStr) throws IOException {
  URL url = new URL(urlStr);
  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  conn.connect();
  return conn.getInputStream();
 }
}
origin: ethereum/ethereumj

private String sendPost(String urlParams) {
  try {
    HttpURLConnection con = (HttpURLConnection) rpcUrl.openConnection();
    //add reuqest header
    con.setRequestMethod("POST");
    // Send post request
    con.setDoOutput(true);
    try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
      wr.writeBytes(urlParams);
      wr.flush();
    }
    int responseCode = con.getResponseCode();
    if (responseCode != 200) {
      throw new RuntimeException("HTTP Response: " + responseCode);
    }
    final StringBuffer response;
    try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
      String inputLine;
      response = new StringBuffer();
      while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
      }
    }
    return response.toString();
  } catch (IOException e) {
    throw new RuntimeException("Error sending POST to " + rpcUrl, e);
  }
}
origin: oracle/helidon

@Override
protected ConfigParser.Content content() throws ConfigException {
  try {
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(GET_METHOD);
    final String mediaType = mediaType(connection.getContentType());
    final Optional<Instant> timestamp;
    if (connection.getLastModified() != 0) {
      timestamp = Optional.of(Instant.ofEpochMilli(connection.getLastModified()));
    } else {
      timestamp = Optional.of(Instant.now());
      LOGGER.fine("Missing GET '" + url + "' response header 'Last-Modified'. Used current time '"
                + timestamp + "' as a content timestamp.");
    }
    Reader reader = new InputStreamReader(connection.getInputStream(),
                       ConfigUtils.getContentCharset(connection.getContentEncoding()));
    return ConfigParser.Content.create(reader, mediaType, timestamp);
  } catch (ConfigException ex) {
    throw ex;
  } catch (Exception ex) {
    throw new ConfigException("Configuration at url '" + url + "' GET is not accessible.", ex);
  }
}
origin: ctripcorp/apollo

InputStreamReader esr = null;
try {
 isr = new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8);
 CharStreams.toString(isr);
} catch (IOException e) {
  esr = new InputStreamReader(errorStream, StandardCharsets.UTF_8);
  try {
   CharStreams.toString(esr);
origin: testcontainers/testcontainers-java

  private String getResponseBody(HttpURLConnection connection) throws IOException {
    BufferedReader reader;
    if (200 <= connection.getResponseCode() && connection.getResponseCode() <= 299) {
      reader = new BufferedReader(new InputStreamReader((connection.getInputStream())));
    } else {
      reader = new BufferedReader(new InputStreamReader((connection.getErrorStream())));
    }

    StringBuilder builder = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
      builder.append(line);
    }
    return builder.toString();
  }
}
origin: bumptech/glide

@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);
}
origin: facebook/stetho

 @Override
 public String call() throws IOException {
  HttpURLConnection connection = (HttpURLConnection)url.openConnection();
  int statusCode = connection.getResponseCode();
  if (statusCode != 200) {
   throw new IOException("Got status code: " + statusCode + " while downloading " +
     "schema with url: " + url.toString());
  }
  InputStream urlStream = connection.getInputStream();
  try {
   return Util.readAsUTF8(urlStream);
  } finally {
   urlStream.close();
  }
 }
}
origin: Alluxio/alluxio

@Override
public void close() throws IOException {
 mOutputStream.close();
 InputStream is = null;
 try {
  // Status 400 and up should be read from error stream.
  // Expecting here 201 Create or 202 Accepted.
  if (mHttpCon.getResponseCode() >= 400) {
   LOG.error("Failed to write data to Swift with error code: " + mHttpCon.getResponseCode());
   is = mHttpCon.getErrorStream();
  } else {
   is = mHttpCon.getInputStream();
  }
  is.close();
 } catch (Exception e) {
  LOG.error(e.getMessage());
  if (is != null) {
   is.close();
  }
 }
 mHttpCon.disconnect();
}
origin: jmdhappy/xxpay-master

/**
 * 以http get方式通信
 *
 * @param url
 * @throws IOException
 */
protected void httpGetMethod(String url) throws IOException {
  HttpURLConnection httpConnection =
      HttpClientUtil.getHttpURLConnection(url);
  this.setHttpRequest(httpConnection);
  httpConnection.setRequestMethod("GET");
  this.responseCode = httpConnection.getResponseCode();
  this.inputStream = httpConnection.getInputStream();
}
origin: googleapis/google-cloud-java

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;
}
origin: google/data-transfer-project

 /**
  * Gets an input stream to an image, given its URL.
  */
 public InputStream get(String urlStr) throws IOException {
  URL url = new URL(urlStr);
  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  conn.connect();
  return conn.getInputStream();
 }
}
origin: oracle/helidon

@Override
protected Data<OverrideData, Instant> loadData() throws ConfigException {
  try {
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(GET_METHOD);
    Instant timestamp;
    if (connection.getLastModified() != 0) {
      timestamp = Instant.ofEpochMilli(connection.getLastModified());
    } else {
      timestamp = Instant.now();
      LOGGER.fine("Missing GET '" + url + "' response header 'Last-Modified'. Used current time '"
                + timestamp + "' as a content timestamp.");
    }
    Reader reader = new InputStreamReader(connection.getInputStream(),
                       ConfigUtils.getContentCharset(connection.getContentEncoding()));
    return new Data<>(Optional.of(OverrideData.create(reader)), Optional.of(timestamp));
  } catch (ConfigException ex) {
    throw ex;
  } catch (Exception ex) {
    throw new ConfigException("Configuration at url '" + url + "' GET is not accessible.", ex);
  }
}
origin: sohutv/cachecloud

private static String getContent(HttpURLConnection urlConn, String encoding) {
  try {
    String responseContent = null;
    InputStream in = urlConn.getInputStream();
    BufferedReader rd = new BufferedReader(new InputStreamReader(in, encoding));
    String tempLine = rd.readLine();
    StringBuffer tempStr = new StringBuffer();
    String crlf = System.getProperty("line.separator");
    while (tempLine != null) {
      tempStr.append(tempLine);
      tempStr.append(crlf);
      tempLine = rd.readLine();
    }
    responseContent = tempStr.toString();
    rd.close();
    in.close();
    return responseContent;
  } catch (Exception e) {
    logger.error(e.getMessage(), e);
    return null;
  }
}
origin: google/physical-web

 urlConnection = (HttpURLConnection) mUrl.openConnection();
 writeToUrlConnection(urlConnection);
 responseCode = urlConnection.getResponseCode();
 inputStream = new BufferedInputStream(urlConnection.getInputStream());
 result = readInputStream(inputStream);
} catch (IOException e) {
origin: alibaba/nacos

private static HttpResult getResult(HttpURLConnection conn) throws IOException {
  int respCode = conn.getResponseCode();
  InputStream inputStream;
  if (HttpURLConnection.HTTP_OK == respCode) {
    inputStream = conn.getInputStream();
  } else {
    inputStream = conn.getErrorStream();
  }
  Map<String, String> respHeaders = new HashMap<String, String>(conn.getHeaderFields().size());
  for (Map.Entry<String, List<String>> entry : conn.getHeaderFields().entrySet()) {
    respHeaders.put(entry.getKey(), entry.getValue().get(0));
  }
  String gzipEncoding = "gzip";
  if (gzipEncoding.equals(respHeaders.get(HttpHeaders.CONTENT_ENCODING))) {
    inputStream = new GZIPInputStream(inputStream);
  }
  HttpResult result = new HttpResult(respCode, IOUtils.toString(inputStream, getCharset(conn)), respHeaders);
  inputStream.close();
  return result;
}
origin: apache/ignite

/**
 * @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());
}
origin: google/data-transfer-project

 /**
  * Gets an input stream to an image, given its URL. Used by {@link FlickrPhotosImporter} to
  * upload the image.
  */
 public BufferedInputStream get(String urlStr) throws IOException {
  URL url = new URL(urlStr);
  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  conn.connect();
  return new BufferedInputStream(conn.getInputStream());
 }
}
java.netHttpURLConnectiongetInputStream

Popular methods of HttpURLConnection

  • getResponseCode
    Returns the response code returned by the remote HTTP server.
  • setRequestMethod
    Sets the request command which will be sent to the remote HTTP server. This method can only be calle
  • setRequestProperty
  • setDoOutput
  • getOutputStream
  • disconnect
    Releases this connection so that its resources may be either reused or closed. Unlike other Java imp
  • setConnectTimeout
  • connect
  • setReadTimeout
  • getErrorStream
    Returns an input stream from the server in the case of an error such as the requested file has not b
  • setDoInput
  • getResponseMessage
    Returns the response message returned by the remote HTTP server.
  • setDoInput,
  • getResponseMessage,
  • getHeaderField,
  • setUseCaches,
  • setInstanceFollowRedirects,
  • getHeaderFields,
  • addRequestProperty,
  • getContentLength,
  • getURL

Popular in Java

  • Making http post requests using okhttp
  • getContentResolver (Context)
  • putExtra (Intent)
  • runOnUiThread (Activity)
  • Socket (java.net)
    Provides a client-side TCP socket.
  • Path (java.nio.file)
  • SortedMap (java.util)
    A map that has its keys ordered. The sorting is according to either the natural ordering of its keys
  • HttpServletRequest (javax.servlet.http)
    Extends the javax.servlet.ServletRequest interface to provide request information for HTTP servlets.
  • JComboBox (javax.swing)
  • JLabel (javax.swing)
  • Top Vim plugins
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now