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:com.surfs.storage.common.util.HttpUtils.java

public static String invokeHttpForGet(String path, String... agrs) throws IOException {
    URL url = new URL(path);
    LogFactory.info("rest url:" + url.toString());
    HttpURLConnection con = null;
    try {//from   w w w.  ja va  2  s .  c  om
        con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.setConnectTimeout(10000);
        con.setReadTimeout(1000 * 60 * 30);
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setUseCaches(false);

        for (String string : agrs) {
            con.setRequestProperty("Content-type", "application/json");
            con.setRequestMethod("POST");
            OutputStream out = con.getOutputStream();
            out.write(string.getBytes("UTF-8"));
        }

        if (con.getResponseCode() != 200)
            throw new ConnectException(con.getResponseMessage());

        InputStream is = con.getInputStream();

        return readResponse(is);

    } catch (IOException e) {
        throw e;
    } finally {
        if (con != null) {
            con.disconnect();
        }
    }
}

From source file:com.fluidops.iwb.luxid.LuxidExtractor.java

public static String authenticate() throws Exception {
    String token = "";

    /* ***** Authentication ****** */
    String auth = "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" "
            + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"> <SOAP-ENV:Body> <ns1:authenticate xmlns:ns1=\"http://luxid.temis.com/ws/types\"> "
            + "<ns1:userName>" + Config.getConfig().getLuxidUserName() + "</ns1:userName> <ns1:userPassword>"
            + Config.getConfig().getLuxidPassword()
            + "</ns1:userPassword> </ns1:authenticate> </SOAP-ENV:Body> </SOAP-ENV:Envelope>";
    URL authURL = new URL(Config.getConfig().getLuxidServerURL());

    HttpURLConnection authconn = (HttpURLConnection) authURL.openConnection();
    authconn.setRequestMethod("POST");
    authconn.setDoOutput(true);/*from  w  w  w .  j  a  v a  2s  .  co m*/

    authconn.getOutputStream().write(auth.getBytes());

    if (authconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
        InputStream stream = authconn.getInputStream();

        InputStreamReader read = new InputStreamReader(stream);
        BufferedReader rd = new BufferedReader(read);

        String line = "";

        if ((line = rd.readLine()) != null) {
            token = line.substring(line.indexOf("<token>") + "<token>".length(), line.indexOf("</token>"));
        }
        rd.close();
    }
    return token;
}

From source file:com.google.android.gcm.demo.app.ServerUtilities.java

/**
 * Issue a POST request to the server.//from   ww w . j  av  a 2s.  c o  m
 *
 * @param endpoint POST address.
 * @param params request parameters.
 *
 * @throws IOException propagated from POST.
 */
private static void post(String endpoint, Map<String, String> params) throws IOException {
    URL url;
    try {
        url = new URL(endpoint);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + endpoint);
    }
    JSONObject jsonObj = new JSONObject(params);
    String body = jsonObj.toString();
    Log.v(TAG, "Posting '" + body + "' to " + url);
    byte[] bytes = body.getBytes();
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setFixedLengthStreamingMode(bytes.length);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        // post the request
        OutputStream out = conn.getOutputStream();
        out.write(bytes);
        out.close();
        // handle the response
        int status = conn.getResponseCode();
        if (status != 200) {
            throw new IOException("Post failed with error code " + status);
        }
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:com.gallatinsystems.common.util.S3Util.java

public static boolean putObjectAcl(String bucketName, String objectKey, ACL acl, String awsAccessId,
        String awsSecretKey) throws IOException {

    final String date = getDate();
    final URL url = new URL(String.format(S3_URL, bucketName, objectKey) + "?acl");
    final String payload = String.format(PUT_PAYLOAD_ACL, date, acl.toString(), bucketName, objectKey);
    final String signature = MD5Util.generateHMAC(payload, awsSecretKey);
    HttpURLConnection conn = null;
    try {/*from  www . ja  va2  s  .  c o m*/

        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("PUT");
        conn.setRequestProperty("Date", date);
        conn.setRequestProperty("x-amz-acl", acl.toString());
        conn.setRequestProperty("Authorization", "AWS " + awsAccessId + ":" + signature);

        int status = conn.getResponseCode();

        if (status != 200 && status != 201) {
            log.severe("Error setting ACL for: " + url.toString());
            log.severe(IOUtils.toString(conn.getInputStream()));
            return false;
        }
        return true;
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:net.maxgigapop.mrs.driver.openstack.OpenStackRESTClient.java

private static String sendPOST(URL url, HttpURLConnection con, String body) throws IOException {

    con.setRequestMethod("POST");
    con.setRequestProperty("Content-type", "application/json");
    con.setRequestProperty("Accept", "application/json");

    con.setDoOutput(true);//  w w  w .jav a 2 s .  com
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(body);
    wr.flush();
    wr.close();

    logger.log(Level.INFO, "Sending POST request to URL : {0}", url);
    int responseCode = con.getResponseCode();
    logger.log(Level.INFO, "Response Code : {0}", responseCode);

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuilder responseStr = new StringBuilder();

    while ((inputLine = in.readLine()) != null) {
        responseStr.append(inputLine);
    }
    in.close();

    return responseStr.toString();

}

From source file:yodlee.ysl.api.io.HTTP.java

public static String doPostRegisterUser(String url, String registerParam, Map<String, String> cobTokens,
        boolean isEncodingNeeded) throws IOException {
    //String processedURL = url+"?registerParam="+registerParam;
    /* String registerUserJson="{"
    + "      \"user\" : {"//from w  ww .  j  a  va 2 s .  c o  m
    + "            \"loginName\" : \"TestT749\","
    + "            \"password\" : \"TESTT@123\","
    + "            \"email\" : \"testet@yodlee.com\","
    + "            \"firstName\" : \"Rehhsty\","
    + "            \"lastName\" :\"ysl\""
    +"             } ,"
            
    + "      \"preference\" : {"
    + "      \"address\" : {"
    + "            \"street\" : \"abcd\","
    + "            \"state\" : \"CA\","
    + "            \"city\" : \"RWS\","
    + "            \"postalCode\" : \"98405\","
    + "            \"countryIsoCode\" : \"USA\""
    +"             } ,"
    + "            \"currency\" : \"USD\","
    + "            \"timeZone\" : \"PST\","
    + "            \"dateFormat\" : \"MM/dd/yyyy\""
    + "}"
    + "}";*/

    //encoding url
    registerParam = java.net.URLEncoder.encode(registerParam, "UTF-8");
    String processedURL = url + "?registerParam=" + registerParam;
    String mn = "doIO(POST : " + processedURL + ", " + registerParam + "sessionTokens : " + " )";
    System.out.println(fqcn + " :: " + mn);
    URL restURL = new URL(processedURL);
    HttpURLConnection conn = (HttpURLConnection) restURL.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("User-Agent", userAgent);
    conn.setRequestProperty("Content-Type", contentTypeURLENCODED);
    conn.setRequestProperty("Content-Type", "text/plain;charset=UTF-8");
    conn.setRequestProperty("Authorization", cobTokens.toString());
    conn.setDoOutput(true);
    conn.setRequestProperty("Accept-Charset", "UTF-8");
    int responseCode = conn.getResponseCode();
    if (responseCode == 200) {
        System.out.println(fqcn + " :: " + mn + " : " + "Sending 'HTTP POST' request");
        System.out.println(fqcn + " :: " + mn + " : " + "Response Code : " + responseCode);
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuilder jsonResponse = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            jsonResponse.append(inputLine);
        }
        in.close();
        System.out.println(fqcn + " :: " + mn + " : " + jsonResponse.toString());
        return new String(jsonResponse);
    } else {
        System.out.println("Invalid input");
        return new String();

    }
}

From source file:Main.java

private static void post(String endpoint, Map<String, String> params) throws IOException {

    URL url;//from ww w . j a v  a2s  . c o  m
    try {
        url = new URL(endpoint);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + endpoint);
    }
    StringBuilder bodyBuilder = new StringBuilder();
    Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator();
    // constructs the POST body using the parameters
    while (iterator.hasNext()) {
        Map.Entry<String, String> param = iterator.next();
        bodyBuilder.append(param.getKey()).append('=').append(param.getValue());
        if (iterator.hasNext()) {
            bodyBuilder.append('&');
        }
    }
    String body = bodyBuilder.toString();
    Log.v(TAG, "Posting '" + body + "' to " + url);
    byte[] bytes = body.getBytes();
    HttpURLConnection conn = null;
    try {
        Log.e("URL", "> " + url);
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setFixedLengthStreamingMode(bytes.length);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        // post the request
        OutputStream out = conn.getOutputStream();
        out.write(bytes);
        out.close();
        // handle the response
        int status = conn.getResponseCode();
        if (status != 200) {
            throw new IOException("Post failed with error code " + status);
        }
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:biz.mosil.webtools.MosilWeb.java

/**
 * ? InputStream//from w ww . j  a  va 2 s  .  c  o  m
 * */
public static final InputStream getInputStream(final String _url) {
    InputStream result = null;

    try {
        URL url = new URL(_url);
        URLConnection conn = url.openConnection();

        if (!(conn instanceof HttpURLConnection)) {
            throw new IOException("This URL Can't Connect!");
        }

        HttpURLConnection httpConn = (HttpURLConnection) conn;
        //????
        httpConn.setAllowUserInteraction(false);
        //??
        httpConn.setInstanceFollowRedirects(true);
        httpConn.setRequestMethod("GET");
        httpConn.connect();

        final int response = httpConn.getResponseCode();

        if (response == HttpURLConnection.HTTP_OK) {
            result = httpConn.getInputStream();
        }

    } catch (MalformedURLException _ex) {
        Log.e("getInputStream", "Malformed URL Exception: " + _ex.toString());
    } catch (IOException _ex) {
        Log.e("getInputStream", "IO Exception: " + _ex.toString());
    }
    return result;
}

From source file:Main.IrcBot.java

public static void postRequest(String pasteCode, PrintWriter out) {
    try {//from w w  w. j a  v  a2  s.  c o m
        String url = "http://pastebin.com/raw.php?i=" + pasteCode;
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        //add reuqest header
        con.setRequestMethod("POST");
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        String urlParameters = "";

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + urlParameters);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine + "\n");
        }
        in.close();

        //print result
        System.out.println(response.toString());

        if (response.length() > 0) {
            IrcBot.postGit(response.toString(), out);
        } else {
            out.println("PRIVMSG #learnprogramming :The PasteBin URL is not valid.");
        }
    } catch (Exception p) {

    }
}

From source file:oneDrive.OneDriveAPI.java

public static String connectWithREST(String url, String method) throws IOException, ProtocolException {
    String newURL = "";
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    // Connect with a REST Method: GET, DELETE, PUT
    con.setRequestMethod(method);//from   w w w  . j a va  2s. com
    //add request header
    con.setReadTimeout(20000);
    con.setConnectTimeout(20000);
    con.setRequestProperty("User-Agent", "Mozilla/5.0");
    if (method.equals(DELETE) || method.equals(PUT) || getSize)
        con.addRequestProperty("Authorization", "Bearer " + ACCESS_TOKEN);

    int responseCode = con.getResponseCode();
    // Read response
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
    newURL = response.toString();

    return newURL;
}