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:com.chiorichan.util.WebUtils.java

public static boolean sendTracking(String category, String action, String label) {
    String url = "http://www.google-analytics.com/collect";
    try {/*w  ww . j a v  a2  s  . co  m*/
        URL urlObj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
        con.setRequestMethod("POST");

        String urlParameters = "v=1&tid=UA-60405654-1&cid=" + Loader.getClientId() + "&t=event&ec=" + category
                + "&ea=" + action + "&el=" + label;

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

        int responseCode = con.getResponseCode();
        Loader.getLogger().fine("Analytics Response [" + category + "]: " + responseCode);

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

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

        return true;
    } catch (IOException e) {
        return false;
    }
}

From source file:com.thyn.backend.gcm.GcmSender.java

public static String addDeviceToDeviceGroup(String notification_key_name, String notification_key,
        String registration_token) {
    String resp = null;/*from   ww w .  ja  va 2  s.  c o  m*/
    try {
        // Prepare JSON containing the GCM message content. What to send and where to send.
        JSONObject jGcmData = new JSONObject();

        // Where to send GCM message.
        if (notification_key_name != null && registration_token != null) {
            jGcmData.put("operation", "add");
            jGcmData.put("notification_key_name", notification_key_name.trim());
            jGcmData.put("notification_key", notification_key.trim());
            jGcmData.put("registration_ids", new JSONArray("[\"" + registration_token + "\"]"));
        } else {
            Logger.logError("Error", new NullPointerException());
            return null;
        }

        // Create connection to send GCM Message request.
        URL url = new URL("https://android.googleapis.com/gcm/notification");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Authorization", "key=" + API_KEY);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("project_id", SENDER_ID);
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);

        // Send GCM message content.
        OutputStream outputStream = conn.getOutputStream();
        outputStream.write(jGcmData.toString().getBytes());

        // Read GCM response.
        InputStream inputStream = conn.getInputStream();
        resp = IOUtils.toString(inputStream);

    } catch (IOException e) {
        Logger.logError("Unable to add Device to Device group.", e);

    }
    return resp;
}

From source file:com.codelanx.codelanxlib.logging.Debugger.java

/**
 * Sends a JSON payload to a URL specified by the string parameter
 * /*  ww w . ja  v  a 2  s  . c om*/
 * @since 0.1.0
 * @version 0.1.0
 * 
 * @param url The URL to report to
 * @param payload The JSON payload to send via POST
 * @throws IOException If the sending failed
 */
private static void send(String url, JSONObject payload) throws IOException {
    URL loc = new URL(url);
    HttpURLConnection http = (HttpURLConnection) loc.openConnection();
    http.setRequestMethod("POST");
    http.setRequestProperty("Content-Type", "application/json");
    http.setUseCaches(false);
    http.setDoOutput(true);
    try (DataOutputStream wr = new DataOutputStream(http.getOutputStream())) {
        wr.writeBytes(payload.toJSONString());
        wr.flush();
    }
}

From source file:com.thyn.backend.gcm.GcmSender.java

public static String createDeviceGroup(String notification_key_name, String registration_token) {
    String Response_Notification_Key = null;
    try {//  ww w.  java2s .  co  m
        // Prepare JSON containing the GCM message content. What to send and where to send.
        JSONObject jGcmData = new JSONObject();

        // Where to send GCM message.
        if (notification_key_name != null && registration_token != null) {
            jGcmData.put("operation", "create");
            jGcmData.put("notification_key_name", notification_key_name.trim());
            jGcmData.put("registration_ids", new JSONArray("[\"" + registration_token + "\"]"));
        } else {
            Logger.logError("Error", new NullPointerException());
            return null;
        }
        Logger.logInfo(jGcmData.toString());

        // Create connection to send GCM Message request.
        URL url = new URL("https://android.googleapis.com/gcm/notification");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Authorization", "key=" + API_KEY);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("project_id", SENDER_ID);
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);

        // Send GCM message content.
        OutputStream outputStream = conn.getOutputStream();
        outputStream.write(jGcmData.toString().getBytes());

        // Read GCM response.
        InputStream inputStream = conn.getInputStream();
        String resp = IOUtils.toString(inputStream);
        Logger.logInfo("the response from GCM server is: " + resp);
        JSONObject jResp = new JSONObject(resp);
        Response_Notification_Key = jResp.getString("notification_key");

    } catch (IOException e) {
        Logger.logError("Unable to create a device group.", e);

    }
    return Response_Notification_Key;
}

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

/**
 * ? InputStream/*  ww  w  .  ja v  a2 s .c om*/
 * */
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:com.mingsoft.weixin.util.UploadDownUtils.java

/**
 * ? ? //from  w  w w .  j  a v  a  2s .c  om
 * @param access_token ??
 * @param msgType image?voice?videothumb
 * @param localFile 
 * @return
 */
@Deprecated
public static String uploadMedia(String access_token, String msgType, String localFile) {
    String media_id = null;
    String url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=" + access_token + "&type="
            + msgType;
    String local_url = localFile;
    try {
        File file = new File(local_url);
        if (!file.exists() || !file.isFile()) {
            log.error("==" + local_url);
            return null;
        }
        URL urlObj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
        con.setRequestMethod("POST"); // Post????get?
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setUseCaches(false); // post??
        // ?
        con.setRequestProperty("Connection", "Keep-Alive");
        con.setRequestProperty("Charset", "UTF-8");

        // 
        String BOUNDARY = "----------" + System.currentTimeMillis();
        con.setRequestProperty("content-type", "multipart/form-data; boundary=" + BOUNDARY);
        // con.setRequestProperty("Content-Type",
        // "multipart/mixed; boundary=" + BOUNDARY);
        // con.setRequestProperty("content-type", "text/html");
        // ?

        // 
        StringBuilder sb = new StringBuilder();
        sb.append("--"); // ////////?
        sb.append(BOUNDARY);
        sb.append("\r\n");
        sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getName() + "\"\r\n");
        sb.append("Content-Type:application/octet-stream\r\n\r\n");
        byte[] head = sb.toString().getBytes("utf-8");
        // ?
        OutputStream out = new DataOutputStream(con.getOutputStream());
        out.write(head);

        // 
        DataInputStream in = new DataInputStream(new FileInputStream(file));
        int bytes = 0;
        byte[] bufferOut = new byte[1024];
        while ((bytes = in.read(bufferOut)) != -1) {
            out.write(bufferOut, 0, bytes);
        }
        in.close();
        // 
        byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// ??
        out.write(foot);
        out.flush();
        out.close();
        /**
         * ????,?????
         */
        // con.getResponseCode();
        try {
            // BufferedReader???URL?
            StringBuffer buffer = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
            String line = null;
            while ((line = reader.readLine()) != null) {
                // System.out.println(line);
                buffer.append(line);
            }
            String respStr = buffer.toString();
            log.debug("==respStr==" + respStr);
            try {
                JSONObject dataJson = JSONObject.parseObject(respStr);

                media_id = dataJson.getString("media_id");
            } catch (Exception e) {
                log.error("==respStr==" + respStr, e);
                try {
                    JSONObject dataJson = JSONObject.parseObject(respStr);
                    return dataJson.getString("errcode");
                } catch (Exception e1) {
                }
            }
        } catch (Exception e) {
            log.error("??POST?" + e);
        }
    } catch (Exception e) {
        log.error("?!=" + local_url);
        log.error("?!", e);
    } finally {
    }
    return media_id;
}

From source file:com.thyn.backend.gcm.GcmSender.java

public static String removeDeviceFromDeviceGroup(String notification_key_name, String notification_key,
        String registration_token) {
    String Response_Notification_Key = null;
    try {/*from  ww  w.  j  a v  a  2s .  c  om*/
        // Prepare JSON containing the GCM message content. What to send and where to send.
        JSONObject jGcmData = new JSONObject();

        // Where to send GCM message.
        if (notification_key_name != null && registration_token != null) {
            jGcmData.put("operation", "remove");
            jGcmData.put("notification_key_name", notification_key_name.trim());
            jGcmData.put("notification_key", notification_key.trim());
            jGcmData.put("registration_ids", new JSONArray("[\"" + registration_token + "\"]"));
        } else {
            Logger.logError("Error", new NullPointerException());
            return null;
        }

        // Create connection to send GCM Message request.
        URL url = new URL("https://android.googleapis.com/gcm/notification");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Authorization", "key=" + API_KEY);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("project_id", SENDER_ID);
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);

        // Send GCM message content.
        OutputStream outputStream = conn.getOutputStream();
        Logger.logInfo("the message sent is" + jGcmData.toString());
        outputStream.write(jGcmData.toString().getBytes());

        // Read GCM response.
        InputStream inputStream = conn.getInputStream();
        String resp = IOUtils.toString(inputStream);
        Logger.logInfo("the response from GSM server is: " + resp);
        JSONObject jResp = new JSONObject(resp);
        Response_Notification_Key = jResp.getString("notification_key");

    } catch (IOException e) {
        Logger.logError("Unable to remove Device from Device group.", e);

    }
    return Response_Notification_Key;
}

From source file:ee.ria.xroad.proxy.ProxyMain.java

private static Map<String, DiagnosticsStatus> checkConnectionToTimestampUrl() {
    Map<String, DiagnosticsStatus> statuses = new HashMap<>();

    for (String tspUrl : ServerConf.getTspUrl()) {
        try {// w w  w  .ja  v a2s  .  c o m
            URL url = new URL(tspUrl);

            log.info("Checking timestamp server status for url {}", url);

            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setConnectTimeout(DIAGNOSTICS_CONNECTION_TIMEOUT_MS);
            con.setReadTimeout(DIAGNOSTICS_READ_TIMEOUT_MS);
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-type", "application/timestamp-query");
            con.connect();

            log.info("Checking timestamp server con {}", con);

            if (con.getResponseCode() != HttpURLConnection.HTTP_OK) {
                log.warn("Timestamp check received HTTP error: {} - {}. Might still be ok",
                        con.getResponseCode(), con.getResponseMessage());
                statuses.put(tspUrl,
                        new DiagnosticsStatus(DiagnosticsErrorCodes.RETURN_SUCCESS, LocalTime.now(), tspUrl));
            } else {
                statuses.put(tspUrl,
                        new DiagnosticsStatus(DiagnosticsErrorCodes.RETURN_SUCCESS, LocalTime.now(), tspUrl));
            }

        } catch (Exception e) {
            log.warn("Timestamp status check failed {}", e);

            statuses.put(tspUrl,
                    new DiagnosticsStatus(DiagnosticsUtils.getErrorCode(e), LocalTime.now(), tspUrl));
        }
    }
    return statuses;

}

From source file:de.minestar.minestarlibrary.utils.PlayerUtils.java

private static String sendHTTPGetRequest(String URL) {
    try {//from w w w . ja  va  2 s .  c o m
        URL urlObject = new URL(URL);
        HttpURLConnection httpConnection = (HttpURLConnection) urlObject.openConnection();

        // optional default is GET
        httpConnection.setRequestMethod("GET");

        // add request header
        httpConnection.setRequestProperty("User-Agent", "Mozilla/5.0");
        int responseCode = httpConnection.getResponseCode();

        // the responseCode must be 200, otherwise the answer is incorrect
        // (i.e. 204 for noContent)
        if (responseCode == 200) {
            BufferedReader in = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            // read response
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // return response as String
            return response.toString();
        }
        return null;
    } catch (Exception e) {
        return null;
    }
}

From source file:disko.DU.java

public static String request(String targetUrl, String method, String text, String contentType)
        throws Exception {
    URL url = new URL(targetUrl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    if (method != null)
        conn.setRequestMethod(method);

    if (contentType != null)
        conn.setRequestProperty("Content-Type", contentType);

    if (text != null) {
        conn.setDoOutput(true);//from  w ww  .jav  a  2  s.c  o m
        conn.setUseCaches(false);
        conn.getOutputStream().write(text.getBytes());
        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        out.write(text.getBytes());
        out.flush();
        out.close();
    }

    if (conn.getResponseCode() != 200)
        throw new RuntimeException("HTTPClient failed: " + conn.getResponseCode());

    StringBuffer responseBuffer = new StringBuffer();
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;
    String eol = new String(new byte[] { 13 });
    while ((line = in.readLine()) != null) {
        responseBuffer.append(line);
        responseBuffer.append(eol);
    }
    in.close();

    return responseBuffer.toString();
}