Example usage for java.net HttpURLConnection setRequestMethod

List of usage examples for java.net HttpURLConnection setRequestMethod

Introduction

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

Prototype

public void setRequestMethod(String method) throws ProtocolException 

Source Link

Document

Set the method for the URL request, one of:
  • GET
  • POST
  • HEAD
  • OPTIONS
  • PUT
  • DELETE
  • TRACE
are legal, subject to protocol restrictions.

Usage

From source file:net.mceoin.cominghome.api.NestUtil.java

private static String getNestAwayStatusCall(String access_token) {

    String away_status = "";

    String urlString = "https://developer-api.nest.com/structures?auth=" + access_token;
    log.info("url=" + urlString);

    StringBuilder builder = new StringBuilder();
    boolean error = false;
    String errorResult = "";

    HttpURLConnection urlConnection = null;
    try {//  ww w  .  j  a  v  a2  s .  c  o m
        URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestProperty("User-Agent", "ComingHomeBackend/1.0");
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setConnectTimeout(15000);
        urlConnection.setReadTimeout(15000);
        //            urlConnection.setChunkedStreamingMode(0);

        //            urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf8");

        boolean redirect = false;

        // normally, 3xx is redirect
        int status = urlConnection.getResponseCode();
        if (status != HttpURLConnection.HTTP_OK) {
            if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                    || status == 307 // Temporary redirect
                    || status == HttpURLConnection.HTTP_SEE_OTHER)
                redirect = true;
        }

        //            System.out.println("Response Code ... " + status);

        if (redirect) {

            // get redirect url from "location" header field
            String newUrl = urlConnection.getHeaderField("Location");

            // open the new connnection again
            urlConnection = (HttpURLConnection) new URL(newUrl).openConnection();
            urlConnection.setRequestMethod("PUT");
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            //                urlConnection.setChunkedStreamingMode(0);

            //                System.out.println("Redirect to URL : " + newUrl);

        }

        int statusCode = urlConnection.getResponseCode();

        log.info("statusCode=" + statusCode);
        if ((statusCode == HttpURLConnection.HTTP_OK)) {
            error = false;

            InputStream response;
            response = urlConnection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(response));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            log.info("response=" + builder.toString());
            JSONObject object = new JSONObject(builder.toString());

            Iterator keys = object.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                JSONObject structure = object.getJSONObject(key);

                if (structure.has("away")) {
                    away_status = structure.getString("away");
                } else {
                    log.info("missing away");
                }
            }

        } else if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
            // bad auth
            error = true;
            errorResult = "Unauthorized";
        } else if (statusCode == HttpURLConnection.HTTP_BAD_REQUEST) {
            error = true;
            InputStream response;
            response = urlConnection.getErrorStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(response));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            log.info("response=" + builder.toString());
            JSONObject object = new JSONObject(builder.toString());

            Iterator keys = object.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                if (key.equals("error")) {
                    // error = Internal Error on bad structure_id
                    errorResult = object.getString("error");
                    log.info("errorResult=" + errorResult);
                }
            }
        } else {
            error = true;
            errorResult = Integer.toString(statusCode);
        }

    } catch (IOException e) {
        error = true;
        errorResult = e.getLocalizedMessage();
        log.warning("IOException: " + errorResult);
    } catch (Exception e) {
        error = true;
        errorResult = e.getLocalizedMessage();
        log.warning("Exception: " + errorResult);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }

    if (error)
        away_status = "Error: " + errorResult;
    return away_status;
}

From source file:gribbit.util.RequestBuilder.java

/**
 * Make a GET or POST request, handling up to 6 redirects, and return the response. If isBinaryResponse is true,
 * returns a byte[] array, otherwise returns the response as a String.
 *///  www.  j a v  a 2  s .  c  om
private static Object makeRequest(String url, String[] keyValuePairs, boolean isGET, boolean isBinaryResponse,
        int redirDepth) {
    if (redirDepth > 6) {
        throw new IllegalArgumentException("Too many redirects");
    }
    HttpURLConnection connection = null;
    try {
        // Add the URL query params if this is a GET request
        String reqURL = isGET ? url + "?" + WebUtils.buildQueryString(keyValuePairs) : url;
        connection = (HttpURLConnection) new URL(reqURL).openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod(isGET ? "GET" : "POST");
        connection.setUseCaches(false);
        connection.setRequestProperty("User-Agent",
                "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) "
                        + "Chrome/43.0.2357.125 Safari/537.36");
        if (!isGET) {
            // Send the body if this is a POST request
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("charset", "utf-8");
            String params = WebUtils.buildQueryString(keyValuePairs);
            connection.setRequestProperty("Content-Length", Integer.toString(params.length()));
            try (DataOutputStream w = new DataOutputStream(connection.getOutputStream())) {
                w.writeBytes(params);
                w.flush();
            }
        }
        if (connection.getResponseCode() == HttpResponseStatus.FOUND.code()) {
            // Follow a redirect. For safety, the params are not passed on, and the method is forced to GET.
            return makeRequest(connection.getHeaderField("Location"), /* keyValuePairs = */null, /* isGET = */
                    true, isBinaryResponse, redirDepth + 1);
        } else if (connection.getResponseCode() == HttpResponseStatus.OK.code()) {
            // For 200 OK, return the text of the response
            if (isBinaryResponse) {
                ByteArrayOutputStream output = new ByteArrayOutputStream(32768);
                IOUtils.copy(connection.getInputStream(), output);
                return output.toByteArray();
            } else {
                StringWriter writer = new StringWriter(1024);
                IOUtils.copy(connection.getInputStream(), writer, "UTF-8");
                return writer.toString();
            }
        } else {
            throw new IllegalArgumentException(
                    "Got non-OK HTTP response code: " + connection.getResponseCode());
        }
    } catch (Exception e) {
        throw new IllegalArgumentException(
                "Exception during " + (isGET ? "GET" : "POST") + " request: " + e.getMessage(), e);
    } finally {
        if (connection != null) {
            try {
                connection.disconnect();
            } catch (Exception e) {
            }
        }
    }
}

From source file:com.gisgraphy.importer.ImporterHelper.java

/**
 * check if an url doesn't return 200 or 3XX code
 * @param urlAsString the url to check/*from   w  w  w .jav a 2  s. com*/
 * @return true if the url exists and is valid
 */
public static boolean checkUrl(String urlAsString) {
    if (urlAsString == null) {
        logger.error("can not check null URL");
        return false;
    }
    URL url;
    try {
        url = new URL(urlAsString);
    } catch (MalformedURLException e) {
        logger.error(urlAsString + " is not a valid url, can not check.");
        return false;
    }
    int responseCode;
    String responseMessage = "NO RESPONSE MESSAGE";
    Object content = "NO CONTENT";
    HttpURLConnection huc;
    try {
        huc = (HttpURLConnection) url.openConnection();
        huc.setRequestMethod("HEAD");
        responseCode = huc.getResponseCode();
        content = huc.getContent();
        responseMessage = huc.getResponseMessage();
    } catch (ProtocolException e) {
        logger.error("can not check url " + e.getMessage(), e);
        return false;
    } catch (IOException e) {
        logger.error("can not check url " + e.getMessage(), e);
        return false;
    }

    if (responseCode == 200 || (responseCode > 300 && responseCode < 400)) {
        logger.info("URL " + urlAsString + " exists");
        return true;
    } else {
        logger.error(urlAsString + " return a " + responseCode + " : " + content + "/" + responseMessage);
        return false;
    }
}

From source file:com.meetingninja.csse.database.UserDatabaseAdapter.java

public static Schedule getSchedule(String userID) throws JsonParseException, JsonMappingException, IOException {
    // Server URL setup
    String _url = getBaseUri().appendPath("Schedule").appendPath(userID).build().toString();
    // establish connection
    URL url = new URL(_url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    // add request header
    conn.setRequestMethod(IRequest.GET);
    addRequestHeader(conn, false);/*ww  w. j ava  2  s . c om*/

    // Get server response
    int responseCode = conn.getResponseCode();
    String response = getServerResponse(conn);

    Schedule sched = parseSchedule(MAPPER.readTree(response));

    conn.disconnect();
    return sched;
}

From source file:com.meetingninja.csse.database.UserDatabaseAdapter.java

public static User getUserInfo(String userID) throws IOException {
    // Server URL setup
    String _url = getBaseUri().appendPath(userID).build().toString();

    // Establish connection
    URL url = new URL(_url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    // add request header
    conn.setRequestMethod(IRequest.GET);
    addRequestHeader(conn, false);//from w w w .ja  va 2 s . c  o m

    // Get server response
    int responseCode = conn.getResponseCode();
    String response = getServerResponse(conn);
    JsonNode userNode = MAPPER.readTree(response);

    User ret = parseUser(userNode);
    ret.setID(userID);
    return ret;
}

From source file:com.webarch.common.net.http.HttpService.java

/**
 * ?url// www.j  a  v a 2  s.c om
 *
 * @param inputStream ?
 * @param fileName    ??
 * @param fileType    
 * @param contentType 
 * @param identity    
 * @return 
 */
public static String uploadMediaFile(String requestUrl, FileInputStream inputStream, String fileName,
        String fileType, String contentType, String identity) {
    String lineEnd = System.getProperty("line.separator");
    String twoHyphens = "--";
    String boundary = "*****";
    String result = null;
    try {
        //?
        URL submit = new URL(requestUrl);
        HttpURLConnection conn = (HttpURLConnection) submit.openConnection();
        //
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        //?
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Charset", DEFAULT_CHARSET);
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        //??
        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + fileName
                + ";Content-Type=\"" + contentType + lineEnd);
        dos.writeBytes(lineEnd);

        byte[] buffer = new byte[8192]; // 8k
        int count = 0;
        while ((count = inputStream.read(buffer)) != -1) {
            dos.write(buffer, 0, count);
        }
        inputStream.close(); //?
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
        dos.flush();

        InputStream is = conn.getInputStream();
        InputStreamReader isr = new InputStreamReader(is, DEFAULT_CHARSET);
        BufferedReader br = new BufferedReader(isr);
        result = br.readLine();
        dos.close();
        is.close();
    } catch (IOException e) {
        logger.error("", e);
    }
    return result;
}

From source file:com.onesignal.OneSignalRestClient.java

private static void makeRequest(String url, String method, JSONObject jsonBody,
        ResponseHandler responseHandler) {
    HttpURLConnection con = null;
    int httpResponse = -1;
    String json = null;//from  w  w w  .  j  a  va  2  s.  c  om

    try {
        con = (HttpURLConnection) new URL(BASE_URL + url).openConnection();
        con.setUseCaches(false);
        con.setDoOutput(true);
        con.setConnectTimeout(TIMEOUT);
        con.setReadTimeout(TIMEOUT);

        if (jsonBody != null)
            con.setDoInput(true);

        con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        con.setRequestMethod(method);

        if (jsonBody != null) {
            String strJsonBody = jsonBody.toString();
            OneSignal.Log(OneSignal.LOG_LEVEL.DEBUG, method + " SEND JSON: " + strJsonBody);

            byte[] sendBytes = strJsonBody.getBytes("UTF-8");
            con.setFixedLengthStreamingMode(sendBytes.length);

            OutputStream outputStream = con.getOutputStream();
            outputStream.write(sendBytes);
        }

        httpResponse = con.getResponseCode();

        InputStream inputStream;
        Scanner scanner;
        if (httpResponse == HttpURLConnection.HTTP_OK) {
            inputStream = con.getInputStream();
            scanner = new Scanner(inputStream, "UTF-8");
            json = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
            scanner.close();
            OneSignal.Log(OneSignal.LOG_LEVEL.DEBUG, method + " RECEIVED JSON: " + json);

            if (responseHandler != null)
                responseHandler.onSuccess(json);
        } else {
            inputStream = con.getErrorStream();
            if (inputStream == null)
                inputStream = con.getInputStream();

            if (inputStream != null) {
                scanner = new Scanner(inputStream, "UTF-8");
                json = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
                scanner.close();
                OneSignal.Log(OneSignal.LOG_LEVEL.WARN, method + " RECEIVED JSON: " + json);
            } else
                OneSignal.Log(OneSignal.LOG_LEVEL.WARN,
                        method + " HTTP Code: " + httpResponse + " No response body!");

            if (responseHandler != null)
                responseHandler.onFailure(httpResponse, json, null);
        }
    } catch (Throwable t) {
        if (t instanceof java.net.ConnectException || t instanceof java.net.UnknownHostException)
            OneSignal.Log(OneSignal.LOG_LEVEL.INFO,
                    "Could not send last request, device is offline. Throwable: " + t.getClass().getName());
        else
            OneSignal.Log(OneSignal.LOG_LEVEL.WARN, method + " Error thrown from network stack. ", t);

        if (responseHandler != null)
            responseHandler.onFailure(httpResponse, null, t);
    } finally {
        if (con != null)
            con.disconnect();
    }
}

From source file:com.meetingninja.csse.database.UserDatabaseAdapter.java

public static List<User> getAllUsers() throws IOException {
    String _url = getBaseUri().appendPath("Users").build().toString();
    // Establish connection
    URL url = new URL(_url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    // add request header
    conn.setRequestMethod(IRequest.GET);
    addRequestHeader(conn, false);/*from   w  ww .  j a v  a  2 s  .c o  m*/

    // Get server response
    int responseCode = conn.getResponseCode();
    String response = getServerResponse(conn);

    List<User> userList = new ArrayList<User>();
    final JsonNode userArray = MAPPER.readTree(response).get(Keys.User.LIST);

    if (userArray.isArray()) {
        for (final JsonNode userNode : userArray) {
            User u = parseUser(userNode);
            // assign and check null and do not add local user
            if (u != null) {
                userList.add(u);
            }
        }
    }

    conn.disconnect();
    return userList;
}

From source file:com.meetingninja.csse.database.UserDatabaseAdapter.java

public static List<Project> getProject(String userID) throws IOException {
    // Server URL setup
    String _url = getBaseUri().appendPath("Projects").appendPath(userID).build().toString();
    URL url = new URL(_url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    // add request header
    conn.setRequestMethod(IRequest.GET);
    addRequestHeader(conn, false);//from  w  ww . j a  va2  s.c o  m

    // Get server response
    int responseCode = conn.getResponseCode();
    String response = getServerResponse(conn);
    // Initialize ObjectMapper
    List<Project> projectList = new ArrayList<Project>();
    final JsonNode projectArray = MAPPER.readTree(response).get(Keys.Project.LIST);
    if (projectArray.isArray()) {
        for (final JsonNode projectNode : projectArray) {
            Project p = new Project();
            p.setProjectID(projectNode.get(Keys.Project.ID).asText());
            ProjectDatabaseAdapter.getProject(p);
            if (p.getProjectID() != null && !p.getProjectID().isEmpty()) {
                projectList.add(p);
            }
        }
    } else {
        Log.e(TAG, "Error parsing user's project list");
    }
    conn.disconnect();
    return projectList;
}

From source file:br.gov.jfrj.siga.base.ConexaoHTTP.java

public static String get(String URL, HashMap<String, String> header, Integer timeout, String payload)
        throws AplicacaoException {

    try {/*from   w  w w  .  j a  v  a2s  .c o  m*/

        HttpURLConnection conn = (HttpURLConnection) new URL(URL).openConnection();

        if (timeout != null) {
            conn.setConnectTimeout(timeout);
            conn.setReadTimeout(timeout);
        }

        //conn.setInstanceFollowRedirects(true);

        if (header != null) {
            for (String s : header.keySet()) {
                conn.setRequestProperty(s, header.get(s));
            }
        }

        System.setProperty("http.keepAlive", "false");

        if (payload != null) {
            byte ab[] = payload.getBytes("UTF-8");
            conn.setRequestMethod("POST");
            // Send post request
            conn.setDoOutput(true);
            OutputStream os = conn.getOutputStream();
            os.write(ab);
            os.flush();
            os.close();
        }

        //StringWriter writer = new StringWriter();
        //IOUtils.copy(conn.getInputStream(), writer, "UTF-8");
        //return writer.toString();
        return IOUtils.toString(conn.getInputStream(), "UTF-8");

    } catch (IOException ioe) {
        throw new AplicacaoException("No foi possvel abrir conexo", 1, ioe);
    }

}