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.thyn.backend.gcm.GcmSender.java

public static void sendMessageToTopic(String topic, String message) {
    try {/*from  w  w  w  . j  a  va2s . c  om*/
        // Prepare JSON containing the GCM message content. What to send and where to send.
        JSONObject jGcmData = new JSONObject();
        JSONObject jData = new JSONObject();
        jData.put("message", message);
        // Where to send GCM message.
        String topicName = "/topics/topic_thyN_" + topic.trim();
        if (topic != null) {
            jGcmData.put("to", topicName);
        } else {
            jGcmData.put("to", "/topics/global");
        }
        // What to send in GCM message.
        jGcmData.put("data", jData);

        // Create connection to send GCM Message request.
        URL url = new URL("https://android.googleapis.com/gcm/send");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Authorization", "key=" + API_KEY);
        conn.setRequestProperty("Content-Type", "application/json");
        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);
        System.out.println(resp);
        System.out.println("Sending message: '" + message + "' to " + topicName);
        System.out.println("Check your device/emulator for notification or logcat for "
                + "confirmation of the receipt of the GCM message.");
    } catch (NullPointerException e) {
        e.printStackTrace();
    } catch (IOException e) {
        System.out.println("Unable to send GCM message.");
        System.out.println("Please ensure that API_KEY has been replaced by the server "
                + "API key, and that the device's registration token is correct (if specified).");
        e.printStackTrace();
    }
}

From source file:dk.kk.ibikecphlib.util.HttpUtils.java

public static JsonResult readLink(String urlString, String method, boolean breakRoute) {
    JsonResult result = new JsonResult();
    if (urlString == null) {
        return result;
    }//  w  w w .ja  v a2 s .  com
    URL url = null;
    HttpURLConnection httpget = null;
    try {
        LOG.d("HttpUtils readlink() " + urlString);
        url = new URL(urlString);
        httpget = (HttpURLConnection) url.openConnection();
        httpget.setDoInput(true);
        httpget.setRequestMethod(method);
        if (breakRoute) {
            httpget.setRequestProperty("Accept", "application/vnd.ibikecph.v1");
        } else {
            httpget.setRequestProperty("Accept", "application/json");
        }
        httpget.setConnectTimeout(CONNECTON_TIMEOUT);
        httpget.setReadTimeout(CONNECTON_TIMEOUT);
        JsonNode root = Util.getJsonObjectMapper().readValue(httpget.getInputStream(), JsonNode.class);
        if (root != null) {
            result.setNode(root);
        }
    } catch (JsonParseException e) {
        LOG.w("HttpUtils readLink() JsonParseException ", e);
        result.error = JsonResult.ErrorCode.APIError;
    } catch (MalformedURLException e) {
        LOG.w("HttpUtils readLink() MalformedURLException", e);
        result.error = JsonResult.ErrorCode.APIError;
    } catch (FileNotFoundException e) {
        LOG.w("HttpUtils readLink() FileNotFoundException", e);
        result.error = JsonResult.ErrorCode.NotFound;
    } catch (IOException e) {
        LOG.w("HttpUtils readLink() IOException", e);
        result.error = JsonResult.ErrorCode.ConnectionError;
    } catch (Exception e) {
    } finally {
        if (httpget != null) {
            httpget.disconnect();
        }
    }
    LOG.d("HttpUtils readLink() "
            + (result != null && result.error == JsonResult.ErrorCode.Success ? "succeeded" : "failed"));
    return result;
}

From source file:eu.geopaparazzi.library.network.NetworkUtilities.java

/**
 * Sends an HTTP GET request to a url//from   w  w w . ja va  2 s . c  om
 *
 * @param urlStr - The URL of the server. (Example: " http://www.yahoo.com/search")
 * @param file the output file. If it is a folder, it tries to get the file name from the header.
 * @param requestParameters - all the request parameters (Example: "param1=val1&param2=val2"). 
 *           Note: This method will add the question mark (?) to the request - 
 *           DO NOT add it yourself
 * @param user
 * @param password
 * @return the file written. 
 * @throws Exception 
 */
public static File sendGetRequest4File(String urlStr, File file, String requestParameters, String user,
        String password) throws Exception {
    if (requestParameters != null && requestParameters.length() > 0) {
        urlStr += "?" + requestParameters;
    }
    HttpURLConnection conn = makeNewConnection(urlStr);
    conn.setRequestMethod("GET");
    // conn.setDoOutput(true);
    conn.setDoInput(true);
    // conn.setChunkedStreamingMode(0);
    conn.setUseCaches(false);

    if (user != null && password != null) {
        conn.setRequestProperty("Authorization", getB64Auth(user, password));
    }
    conn.connect();

    if (file.isDirectory()) {
        // try to get the header
        String headerField = conn.getHeaderField("Content-Disposition");
        String fileName = null;
        if (headerField != null) {
            String[] split = headerField.split(";");
            for (String string : split) {
                String pattern = "filename=";
                if (string.toLowerCase().startsWith(pattern)) {
                    fileName = string.replaceFirst(pattern, "");
                    break;
                }
            }
        }
        if (fileName == null) {
            // give a name
            fileName = "FILE_" + LibraryConstants.TIMESTAMPFORMATTER.format(new Date());
        }
        file = new File(file, fileName);
    }

    InputStream in = null;
    FileOutputStream out = null;
    try {
        in = conn.getInputStream();
        out = new FileOutputStream(file);

        byte[] buffer = new byte[(int) maxBufferSize];
        int bytesRead = in.read(buffer, 0, (int) maxBufferSize);
        while (bytesRead > 0) {
            out.write(buffer, 0, bytesRead);
            bytesRead = in.read(buffer, 0, (int) maxBufferSize);
        }
        out.flush();

    } finally {
        if (in != null)
            in.close();
        if (out != null)
            out.close();
    }
    return file;
}

From source file:io.apiman.manager.test.es.ESMetricsAccessorTest.java

private static void loadTestData() throws Exception {
    String url = "http://localhost:6500/_bulk";
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestMethod("POST");
    conn.setDoInput(true);//from w ww. j a v  a  2  s.com
    conn.setDoOutput(true);
    OutputStream os = conn.getOutputStream();
    InputStream is = ESMetricsAccessorTest.class.getResourceAsStream("bulk-metrics-data.txt");
    IOUtils.copy(is, os);
    IOUtils.closeQuietly(is);
    IOUtils.closeQuietly(os);
    if (conn.getResponseCode() > 299) {
        IOUtils.copy(conn.getInputStream(), System.err);
        throw new IOException("Bulk load of data failed with: " + conn.getResponseMessage());
    }

    client.execute(new Refresh.Builder().addIndex("apiman_metrics").refresh(true).build());
}

From source file:org.wso2.carbon.appmanager.integration.ui.Util.HttpUtil.java

public static HttpResponse doPut(URL endpoint, String postBody, Map<String, String> headers) throws Exception {
    HttpURLConnection urlConnection = null;
    try {/*from www  . jav  a  2s. c o  m*/
        urlConnection = (HttpURLConnection) endpoint.openConnection();
        try {
            urlConnection.setRequestMethod("PUT");
        } catch (ProtocolException e) {
            throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e);
        }
        urlConnection.setDoOutput(true);

        if (headers != null && headers.size() > 0) {
            Iterator<String> itr = headers.keySet().iterator();
            while (itr.hasNext()) {
                String key = itr.next();
                urlConnection.setRequestProperty(key, headers.get(key));
            }
        }
        OutputStream out = urlConnection.getOutputStream();
        try {
            Writer writer = new OutputStreamWriter(out, "UTF-8");
            writer.write(postBody);
            writer.close();
        } catch (IOException e) {
            throw new Exception("IOException while puting data", e);
        } finally {
            if (out != null) {
                out.close();
            }
        }

        // Get the response
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = null;
        try {
            rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
        } catch (FileNotFoundException ignored) {
        } finally {
            if (rd != null) {
                rd.close();
            }
        }
        Iterator<String> itr = urlConnection.getHeaderFields().keySet().iterator();
        Map<String, String> responseHeaders = new HashMap();
        while (itr.hasNext()) {
            String key = itr.next();
            if (key != null) {
                responseHeaders.put(key, urlConnection.getHeaderField(key));
            }
        }
        return new HttpResponse(sb.toString(), urlConnection.getResponseCode(), responseHeaders);

    } catch (IOException e) {
        throw new Exception("Connection error (is server running at " + endpoint + " ?): " + e);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

From source file:com.magnet.tools.tests.MagnetToolStepDefs.java

public static boolean ping(String url, int maxSecs) {

    long startMs = System.currentTimeMillis();
    try {/*w w  w.  j  a  v  a  2  s  .  co  m*/
        while (maxSecs >= ((System.currentTimeMillis() - startMs) / 1000)) {
            try {
                HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
                connection.setConnectTimeout(5000);
                connection.setReadTimeout(5000);
                connection.setRequestMethod("GET");
                int responseCode = connection.getResponseCode();
                if (200 <= responseCode && responseCode <= 399) {
                    return true;
                } else {
                    Thread.sleep(2000);
                }
            } catch (IOException exception) {
                Thread.sleep(2000);
            }

        }
    } catch (InterruptedException ie) {
        // IGNORE
    }
    return false;
}

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

/**
 * //  w w  w  .  j av a  2 s.  com
 *
 * @param media_id ?ID
 * @param identity 
 * @param filepath ?(????)
 * @return ?(???)error
 */
public static String downLoadMediaFile(String requestUrl, String media_id, String identity, String filepath) {
    String mediaLocalURL = "error";
    InputStream inputStream = null;
    FileOutputStream fileOutputStream = null;
    DataOutputStream dataOutputStream = null;
    try {
        URL downLoadURL = new URL(requestUrl);
        // URL
        HttpURLConnection connection = (HttpURLConnection) downLoadURL.openConnection();
        //?
        connection.setRequestMethod("GET");
        // 
        connection.connect();
        //?,?text,json
        if (connection.getContentType().equalsIgnoreCase("text/plain")) {
            // BufferedReader???URL?
            inputStream = connection.getInputStream();
            BufferedReader read = new BufferedReader(new InputStreamReader(inputStream, DEFAULT_CHARSET));
            String valueString = null;
            StringBuffer bufferRes = new StringBuffer();
            while ((valueString = read.readLine()) != null) {
                bufferRes.append(valueString);
            }
            inputStream.close();
            String errMsg = bufferRes.toString();
            JSONObject jsonObject = JSONObject.parseObject(errMsg);
            logger.error("???" + (jsonObject.getInteger("errcode")));
            mediaLocalURL = "error";
        } else {
            BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
            String ds = connection.getHeaderField("Content-disposition");
            //??
            String fullName = ds.substring(ds.indexOf("filename=\"") + 10, ds.length() - 1);
            //?--??
            String preffix = fullName.substring(0, fullName.lastIndexOf("."));
            //?
            String suffix = fullName.substring(preffix.length() + 1);
            //
            String length = connection.getHeaderField("Content-Length");
            //
            String type = connection.getHeaderField("Content-Type");
            //
            byte[] buffer = new byte[8192]; // 8k
            int count = 0;
            mediaLocalURL = filepath + File.separator;
            File file = new File(mediaLocalURL);
            if (!file.exists()) {
                file.mkdirs();
            }
            File mediaFile = new File(mediaLocalURL, fullName);
            fileOutputStream = new FileOutputStream(mediaFile);
            dataOutputStream = new DataOutputStream(fileOutputStream);
            while ((count = bis.read(buffer)) != -1) {
                dataOutputStream.write(buffer, 0, count);
            }
            //?
            mediaLocalURL += fullName;
            bis.close();
            dataOutputStream.close();
            fileOutputStream.close();
        }
    } catch (IOException e) {
        logger.error("?", e);
    }
    return mediaLocalURL;
}

From source file:org.wso2.carbon.appmanager.integration.ui.Util.HttpUtil.java

public static HttpResponse doPost(URL endpoint, String postBody, Map<String, String> headers) throws Exception {
    HttpURLConnection urlConnection = null;
    try {/*from  ww  w .ja v  a2  s . c o m*/
        urlConnection = (HttpURLConnection) endpoint.openConnection();
        try {
            urlConnection.setRequestMethod("POST");
        } catch (ProtocolException e) {
            throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e);
        }
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setUseCaches(false);
        urlConnection.setAllowUserInteraction(false);

        // setting headers
        if (headers != null && headers.size() > 0) {
            Iterator<String> itr = headers.keySet().iterator();
            while (itr.hasNext()) {
                String key = itr.next();
                urlConnection.setRequestProperty(key, headers.get(key));
            }
        }

        OutputStream out = urlConnection.getOutputStream();
        try {
            Writer writer = new OutputStreamWriter(out, "UTF-8");
            writer.write(postBody);
            writer.close();
        } catch (IOException e) {
            throw new Exception("IOException while posting data", e);
        } finally {
            if (out != null) {
                out.close();
            }
        }

        // Get the response
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = null;
        try {
            rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
        } catch (FileNotFoundException ignored) {
        } finally {
            if (rd != null) {
                rd.close();
            }
        }
        Iterator<String> itr = urlConnection.getHeaderFields().keySet().iterator();
        Map<String, String> responseHeaders = new HashMap();
        while (itr.hasNext()) {
            String key = itr.next();
            if (key != null) {
                responseHeaders.put(key, urlConnection.getHeaderField(key));
            }
        }
        return new HttpResponse(sb.toString(), urlConnection.getResponseCode(), responseHeaders);

    } catch (IOException e) {
        throw new Exception("Connection error (is server running at " + endpoint + " ?): " + e);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

From source file:com.gson.util.HttpKit.java

/**
 * ?http?//from w ww  . j  a  va  2 s. c o m
 * @param url
 * @param method
 * @param headers
 * @return
 * @throws IOException
 */
private static HttpURLConnection initHttp(String url, String method, Map<String, String> headers)
        throws IOException {
    URL _url = new URL(url);
    HttpURLConnection http = (HttpURLConnection) _url.openConnection();
    // 
    http.setConnectTimeout(25000);
    // ? --??
    http.setReadTimeout(25000);
    http.setRequestMethod(method);
    http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    http.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
    if (null != headers && !headers.isEmpty()) {
        for (Entry<String, String> entry : headers.entrySet()) {
            http.setRequestProperty(entry.getKey(), entry.getValue());
        }
    }
    http.setDoOutput(true);
    http.setDoInput(true);
    http.connect();
    return http;
}

From source file:com.wisdombud.right.client.common.HttpKit.java

private static HttpURLConnection getHttpConnection(String url, String method, Map<String, String> headers)
        throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
    final URL _url = new URL(url);
    final HttpURLConnection conn = (HttpURLConnection) _url.openConnection();
    if (conn instanceof HttpsURLConnection) {
        ((HttpsURLConnection) conn).setSSLSocketFactory(sslSocketFactory);
        ((HttpsURLConnection) conn).setHostnameVerifier(trustAnyHostnameVerifier);
    }//ww w  .ja  v  a2 s  .  co m

    conn.setRequestMethod(method);
    conn.setDoOutput(true);
    conn.setDoInput(true);

    conn.setConnectTimeout(19000);
    conn.setReadTimeout(19000);

    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");

    if (headers != null && !headers.isEmpty()) {
        for (final Entry<String, String> entry : headers.entrySet()) {
            conn.setRequestProperty(entry.getKey(), entry.getValue());
        }
    }

    return conn;
}