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

How to use
getResponseCode
method
in
java.net.HttpURLConnection

Best Java code snippets using java.net.HttpURLConnection.getResponseCode (Showing top 20 results out of 17,082)

Refine searchRefine arrow

  • URL.openConnection
  • URL.<init>
  • HttpURLConnection.setRequestMethod
  • URLConnection.getInputStream
  • URLConnection.setRequestProperty
  • 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: stackoverflow.com

 HttpURLConnection httpConn = (HttpURLConnection)_urlConnection;
InputStream _is;
if (httpConn.getResponseCode() < 400) {
  _is = httpConn.getInputStream();
} else {
   /* error from server */
  _is = httpConn.getErrorStream();
}
origin: stackoverflow.com

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

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

@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());
  }
}
origin: robovm/robovm

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;
}
origin: stanfordnlp/CoreNLP

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);
 }
}
origin: stackoverflow.com

 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
origin: eclipse-vertx/vert.x

public static int getHttpCode() throws IOException {
 return ((HttpURLConnection) new URL("http://localhost:8080")
   .openConnection()).getResponseCode();
}
origin: Netflix/eureka

  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;
  }
}
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: apache/storm

@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);
  }
}
origin: stackoverflow.com

 HttpURLConnection httpConn = (HttpURLConnection)connection;
InputStream is;
if (httpConn.getResponseCode() >= 400) {
  is = httpConn.getErrorStream();
} else {
  is = httpConn.getInputStream();
}
origin: stackoverflow.com

 URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();

int code = connection.getResponseCode();
origin: eclipse-vertx/vert.x

private int getHttpCode() throws IOException {
 return ((HttpURLConnection) new URL("http://localhost:8080")
   .openConnection()).getResponseCode();
}
origin: micronaut-projects/micronaut-core

/**
 * @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;
}
origin: stackoverflow.com

 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();
  }
}
origin: stackoverflow.com

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");
java.netHttpURLConnectiongetResponseCode

Javadoc

Returns the response code returned by the remote HTTP server.

Popular methods of HttpURLConnection

  • getInputStream
  • 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)
  • CodeWhisperer alternatives
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