Example usage for java.net HttpURLConnection getResponseCode

List of usage examples for java.net HttpURLConnection getResponseCode

Introduction

In this page you can find the example usage for java.net HttpURLConnection getResponseCode.

Prototype

public int getResponseCode() throws IOException 

Source Link

Document

Gets the status code from an HTTP response message.

Usage

From source file:br.com.autonomiccs.autonomic.plugin.common.utils.HttpUtils.java

public String executeHttpGetRequest(URL url) throws IOException {
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("GET");
    int responseCode = con.getResponseCode();
    if (responseCode != 200) {
        return String.format("Error in HTTP GET : code [%d]", responseCode);
    }//from   w  ww. j  a  v a2  s. c  om
    StringWriter output = new StringWriter();
    IOUtils.copy(con.getInputStream(), output);
    return output.toString();
}

From source file:add.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  w w w. j ava 2 s . co  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

    EmployeeJDBCTemplate employeeJDBCTemplate = (EmployeeJDBCTemplate) context.getBean("employeeJDBCTemplate");

    System.out.println("Creating Records...");

    employeeJDBCTemplate.create(request.getParameter("name"), request.getParameter("email"),
            request.getParameter("mobile"), request.getParameter("department"), request.getParameter("salary"));
    URL obj = new URL("http://shashankgaurav.com/sendmail.php?email=" + request.getParameter("email"));

    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    int responseCode = con.getResponseCode();

    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */

        out.println("Created");
    }
}

From source file:com.maltera.technologic.maven.mcforge.detect.CentralHashDetector.java

public void detect(Target target) throws MojoFailureException, MojoExecutionException {
    try {/* w w  w.  ja  v  a  2  s.c om*/
        final URL url = new URL("http://search.maven.org/solrsearch/select" + "?q=1:\"" + target.getHash()
                + "\"&rows=1&wt=json");
        final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.connect();

        if (200 != conn.getResponseCode()) {
            throw new MojoFailureException("error querying Nexus on Maven Central: " + conn.getResponseCode()
                    + " " + conn.getResponseMessage());
        }

        final JsonNode result = jackson.readTree(conn.getInputStream());
        final JsonNode artifact = result.path("response").path("docs").path(0);

        if (!artifact.isMissingNode()) {
            target.foundArtifact(
                    new DefaultArtifact(artifact.path("g").textValue(), artifact.path("a").textValue(),
                            artifact.path("p").textValue(), artifact.path("v").textValue()),
                    "central");
        }
    } catch (IOException caught) {
        throw new MojoFailureException("error searching Maven Central", caught);
    }
}

From source file:com.forgerock.wisdom.oauth2.info.internal.OpenAmIntrospectionService.java

@Override
public TokenInfo introspect(final String token) {
    String tokenInfoRequest = format("%s/oauth2/tokeninfo?access_token=%s&realm=%s", baseUrl, token, realm);

    try {//from w  ww. j  a va2 s  .c  om
        HttpURLConnection connection = (HttpURLConnection) new URL(tokenInfoRequest).openConnection();
        int code = connection.getResponseCode();
        if (code != 200) {
            return TokenInfo.INVALID;
        }

        try (InputStream stream = connection.getInputStream()) {
            JsonNode node = mapper.readTree(stream);
            List<String> scopes = new ArrayList<>();
            for (JsonNode scope : node.get("scope")) {
                scopes.add(scope.asText());
            }
            long expiresIn = node.get("expires_in").asLong();
            return new TokenInfo(true, expiresIn, scopes);
        }

    } catch (IOException e) {
        return TokenInfo.INVALID;
    }
}

From source file:self.philbrown.droidQuery.XMLResponseHandler.java

public Document handleResponse(HttpURLConnection connection) throws ClientProtocolException, IOException {
    int statusCode = connection.getResponseCode();

    if (statusCode >= 300) {
        Log.e("droidQuery", "HTTP Response Error " + statusCode + ":" + connection.getResponseMessage());
    }// w w  w  .  j  ava  2 s.  c o m

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    InputStream is = null;
    try {
        is = AjaxUtil.getInputStream(connection);
        return factory.newDocumentBuilder().parse(is);
    } catch (IllegalStateException e) {
        throw e;
    } catch (SAXException e) {
        throw new IOException();
    } catch (ParserConfigurationException e) {
        throw new IOException();
    } catch (NullPointerException e) {
        return null;
    } finally {
        if (is != null)
            is.close();
    }
}

From source file:at.mukprojects.giphy4j.dao.HttpRequestSender.java

private Response send(HttpURLConnection connection) throws IOException {
    connection.connect();//from w  w w. jav  a 2 s  .  c  o  m

    if (connection.getResponseCode() != 200) {
        throw new IOException("Bad response! Code: " + connection.getResponseCode());
    }

    Map<String, String> headers = new HashMap<String, String>();
    for (String key : connection.getHeaderFields().keySet()) {
        headers.put(key, connection.getHeaderFields().get(key).get(0));
    }

    String body = null;
    InputStream inputStream = null;

    try {
        inputStream = connection.getInputStream();

        String encoding = connection.getContentEncoding();
        encoding = encoding == null ? Giphy4JConstants.ENCODING : encoding;

        body = IOUtils.toString(inputStream, encoding);
    } catch (IOException e) {
        throw new IOException(e);
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
    }

    if (body == null) {
        throw new IOException("Unparseable response body! \n {" + body + "}");
    }

    Response response = new Response(headers, body);

    return response;
}

From source file:com.orange.oidc.secproxy_service.HttpOpenidConnect.java

/**
 * Apply normalization rules to the identifier supplied by the End-User 
 * to determine the Resource and Host. Then make an HTTP GET request to
 * the host's WebFinger endpoint to obtain the location of the requested 
 * service/*from w  w w .  ja v a  2s. c  om*/
 * return the issuer location ("href")
 * @param user_input , domain
 * @return
 */

public static String webfinger(String userInput, String serverUrl) {
    // android.os.Debug.waitForDebugger();

    String result = ""; // result of the http request (a json object
    // converted to string)
    String postUrl = "";
    String host = null;
    String href = null;

    // URI identifying the type of service whose location is being requested
    final String rel = "http://openid.net/specs/connect/1.0/issuer";

    if (!isEmpty(userInput)) {

        try {
            // normalizes this URI's path
            URI uri = new URI(userInput).normalize();
            String[] parts = uri.getRawSchemeSpecificPart().split("@");

            if (!isEmpty(serverUrl)) {
                // use serverUrl if specified
                if (serverUrl.startsWith("https://")) {
                    host = serverUrl.substring(8);
                } else if (serverUrl.startsWith("http://")) {
                    host = serverUrl.substring(7);
                } else {
                    host = serverUrl;
                }
            } else if (parts.length > 1) {
                // the user is using an E-Mail Address Syntax
                host = parts[parts.length - 1];
            } else {
                // the user is using an other syntax
                host = uri.getHost();
            }

            // check if host is valid
            if (host == null) {
                return null;
            }

            if (!host.endsWith("/"))
                host += "/";
            postUrl = "https://" + host + ".well-known/webfinger?resource=" + userInput + "&rel=" + rel;

            // log the request
            Logd(TAG, "Web finger request\n GET " + postUrl + "\n HTTP /1.1" + "\n Host: " + host);
            // Send an HTTP get request with the resource and rel parameters
            HttpURLConnection huc = getHUC(postUrl);
            huc.setDoOutput(true);
            huc.setRequestProperty("Content-Type", "application/jrd+json");
            huc.connect();

            try {

                int responseCode = huc.getResponseCode();
                Logd(TAG, "webfinger responseCode: " + responseCode);
                // if 200, read http body
                if (responseCode == 200) {
                    InputStream is = huc.getInputStream();
                    result = convertStreamToString(is);
                    is.close();
                    Logd(TAG, "webfinger result: " + result);

                    // The response is a json object and the issuer location
                    // is returned as the value of the href member
                    // a links array element with the rel member value
                    // http://openid.net/specs/connect/1.0/issuer
                    JSONObject jo = new JSONObject(result);
                    JSONObject links = jo.getJSONArray("links").getJSONObject(0);
                    href = links.getString("href");
                    Logd(TAG, "webfinger reponse href: " + href);

                } else {
                    // why the request didn't succeed
                    href = huc.getResponseMessage();
                }

                // close connection
                huc.disconnect();
            } catch (IOException ioe) {
                Logd(TAG, "webfinger io exception: " + huc.getErrorStream());
                ioe.printStackTrace();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    } else {
        // the user_input is empty
        href = "no identifier detected!!\n";
    }
    return href;
}

From source file:cn.ctyun.amazonaws.internal.EC2MetadataClient.java

/**
 * Reads a response from the Amazon EC2 Instance Metadata Service and
 * returns the content as a string.// www.  j a  v a 2  s.c  o m
 *
 * @param connection
 *            The connection to the Amazon EC2 Instance Metadata Service.
 *
 * @return The content contained in the response from the Amazon EC2
 *         Instance Metadata Service.
 *
 * @throws IOException
 *             If any problems ocurred while reading the response.
 */
private String readResponse(HttpURLConnection connection) throws IOException {
    if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND)
        throw new AmazonClientException("The requested metadata is not found at " + connection.getURL());

    InputStream inputStream = connection.getInputStream();

    try {
        StringBuilder buffer = new StringBuilder();
        while (true) {
            int c = inputStream.read();
            if (c == -1)
                break;
            buffer.append((char) c);
        }

        return buffer.toString();
    } finally {
        inputStream.close();
    }
}

From source file:self.philbrown.droidQuery.ScriptResponseHandler.java

public ScriptResponse handleResponse(HttpURLConnection connection) throws ClientProtocolException, IOException {
    int statusCode = connection.getResponseCode();

    if (statusCode >= 300) {
        Log.e("droidQuery", "HTTP Response Error " + statusCode + ":" + connection.getResponseMessage());
    }/*from  w  w  w  . java2  s. co  m*/

    ScriptResponse script = new ScriptResponse();
    InputStream stream = AjaxUtil.getInputStream(connection);
    script.text = Ajax.parseText(stream);
    //new line characters currently represent a new command. 
    //Although one file can be all one line, it will be executed as a shell script.
    //for something else, the first line should contain be: #!<shell>\n, where <shell> points
    //to the shell that should be used.
    String[] commands = script.text.split("\n");
    script.script = new Script(context, commands);
    try {
        script.output = script.script.execute();
    } catch (Throwable t) {
        //could not execute script
        script.output = null;
    } finally {
        if (stream != null) {
            stream.close();
        }
    }
    return script;
}

From source file:com.example.gauth.GAuthTask.java

/**
 * Contacts the user info server to get the profile of the user and extracts the first name
 * of the user from the profile. In order to authenticate with the user info server the method
 * first fetches an access token from Google Play services.
 *
 * @throws java.io.IOException    if communication with user info server failed.
 * @throws org.json.JSONException if the response from the server could not be parsed.
 *///from  w ww . jav a2  s.  co m
private void fetchUserFromProfileServer() throws IOException, JSONException {
    String token = fetchToken();
    if (token == null) {
        // error has already been handled in fetchToken()
        return;
    }
    URL url = new URL("https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + token);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    int sc = con.getResponseCode();
    if (sc == 200) {
        InputStream is = con.getInputStream();
        String response = readResponse(is);
        mActivity.showResult(response);
        is.close();
    } else if (sc == 401) {
        GoogleAuthUtil.invalidateToken(mActivity, token);
        onError("Server auth error, please try again.", null);
        Log.i(TAG, "Server auth error: " + readResponse(con.getErrorStream()));
    } else {
        onError("Server returned the following error code: " + sc, null);
    }
}