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:no.ntnu.wifimanager.ServerUtilities.java

/**
 * Issue a POST request to server.//  w w  w. j a v  a2 s  .  c  om
 *
 * @param serverUrl POST address.
 * @param params request parameters.
 *
 * @throws IOException propagated from POST.
 */
public static void HTTPpost(String serverUrl, Map<String, String> params, String contentType)
        throws IOException {
    URL url;
    try {
        url = new URL(serverUrl);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + serverUrl);
    }
    StringBuilder bodyBuilder = new StringBuilder();
    Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
    // constructs the POST body using the parameters
    while (iterator.hasNext()) {
        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(LOG_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", contentType);
        // 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:edu.dartmouth.cs.dartcard.HttpUtilities.java

private static HttpURLConnection makePostConnection(URL url, byte[] bytes) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);//from  w  w w  .  j a v  a 2s . c om
    conn.setUseCaches(false);
    conn.setFixedLengthStreamingMode(bytes.length);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

    // Add in API key
    String authKey = new String(Base64.encodeBase64((key + ":").getBytes()));
    conn.setRequestProperty("Authorization", "Basic " + authKey);

    OutputStream out = conn.getOutputStream();
    out.write(bytes);
    out.close();

    return conn;
}

From source file:io.jari.geenstijl.API.API.java

public static String postUrl(String url, List<NameValuePair> params, String cheader, boolean refererandorigin)
        throws IOException {
    HttpURLConnection http = (HttpURLConnection) new URL(url).openConnection();
    http.setRequestMethod("POST");
    http.setDoInput(true);//from   w w  w. jav  a  2 s.c o m
    http.setDoOutput(true);
    if (cheader != null)
        http.setRequestProperty("Cookie", cheader);
    if (refererandorigin) {
        http.setRequestProperty("Referer",
                "http://www.geenstijl.nl/mt/archieven/2014/01/brein_chanteert_ondertitelaars.html");
        http.setRequestProperty("Origin", "http://www.geenstijl.nl");
    }
    OutputStream os = http.getOutputStream();
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
    writer.write(getQuery(params));
    writer.flush();
    writer.close();
    os.close();

    http.connect();

    InputStream in = http.getInputStream();
    String encoding = http.getContentEncoding();
    encoding = encoding == null ? "UTF-8" : encoding;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buf = new byte[8192];
    int len = 0;
    while ((len = in.read(buf)) != -1) {
        baos.write(buf, 0, len);
    }
    return new String(baos.toByteArray(), encoding);
}

From source file:LNISmokeTest.java

/**
 * Get an item with WebDAV GET http request.
 * /*from   w w w  .j  av  a  2s. co  m*/
 * @param lni the lni
 * @param itemHandle the item handle
 * @param packager the packager
 * @param output the output
 * @param endpoint the endpoint
 * 
 * @throws RemoteException the remote exception
 * @throws ProtocolException the protocol exception
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws FileNotFoundException the file not found exception
 */
private static void doGet(LNISoapServlet lni, String itemHandle, String packager, String output,
        String endpoint)
        throws java.rmi.RemoteException, ProtocolException, IOException, FileNotFoundException {
    // assemble URL from chopped endpoint-URL and relative URI
    String itemURI = doLookup(lni, itemHandle, null);
    URL url = LNIClientUtils.makeDAVURL(endpoint, itemURI, packager);
    System.err.println("DEBUG: GET from URL: " + url.toString());

    // connect with GET method, then copy file over.
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setDoInput(true);
    fixBasicAuth(url, conn);
    conn.connect();
    int status = conn.getResponseCode();
    if (status < 200 || status >= 300) {
        die(status, "HTTP error, status=" + String.valueOf(status) + ", message=" + conn.getResponseMessage());
    }

    InputStream in = conn.getInputStream();
    OutputStream out = new FileOutputStream(output);
    copyStream(in, out);
    in.close();
    out.close();

    System.err.println("DEBUG: Created local file " + output);
    System.err.println(
            "RESULT: Status=" + String.valueOf(conn.getResponseCode()) + " " + conn.getResponseMessage());
}

From source file:loadTest.loadTestLib.LUtil.java

public static boolean startDockerBuild() throws IOException, InterruptedException {
    if (useDocker) {
        if (runInDockerCluster) {

            HashMap<String, Integer> dockerNodes = getDockerNodes();
            String dockerTar = LUtil.class.getClassLoader().getResource("docker/loadTest.tar").toString()
                    .substring(5);/*www  .  j a va 2  s.c  o  m*/
            ExecutorService exec = Executors.newFixedThreadPool(dockerNodes.size());

            dockerError = false;
            doneDockers = 0;

            for (Entry<String, Integer> entry : dockerNodes.entrySet()) {
                exec.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String url = entry.getKey() + "/images/vauvenal5/loadtest";
                            URL obj = new URL(url);
                            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
                            con.setRequestMethod("DELETE");
                            con.setRequestProperty("force", "true");
                            int responseCode = con.getResponseCode();
                            con.disconnect();

                            url = entry.getKey()
                                    + "/build?t=vauvenal5/loadtest&dockerfile=./loadTest/Dockerfile";
                            obj = new URL(url);
                            con = (HttpURLConnection) obj.openConnection();
                            con.setRequestMethod("POST");
                            con.setRequestProperty("Content-type", "application/tar");
                            con.setDoOutput(true);
                            File file = new File(dockerTar);
                            FileInputStream fileStr = new FileInputStream(file);
                            byte[] b = new byte[(int) file.length()];
                            fileStr.read(b);
                            con.getOutputStream().write(b);
                            con.getOutputStream().flush();
                            con.getOutputStream().close();

                            responseCode = con.getResponseCode();

                            if (responseCode != 200) {
                                dockerError = true;
                            }

                            String msg = "";

                            do {
                                Thread.sleep(5000);
                                msg = "";
                                url = entry.getKey() + "/images/json";
                                obj = new URL(url);
                                HttpURLConnection con2 = (HttpURLConnection) obj.openConnection();
                                con2.setRequestMethod("GET");
                                responseCode = con2.getResponseCode();

                                BufferedReader in = new BufferedReader(
                                        new InputStreamReader(con2.getInputStream()));
                                String line = null;

                                while ((line = in.readLine()) != null) {
                                    msg += line;
                                }

                                con2.disconnect();
                            } while (!msg.contains("vauvenal5/loadtest"));

                            con.disconnect();
                            doneDockers++;
                        } catch (MalformedURLException ex) {
                            dockerError = true;
                        } catch (FileNotFoundException ex) {
                            dockerError = true;
                        } catch (IOException ex) {
                            dockerError = true;
                        } catch (InterruptedException ex) {
                            dockerError = true;
                        }
                    }
                });
            }

            while (doneDockers < dockerNodes.size()) {
                Thread.sleep(5000);
            }

            return !dockerError;
        }

        //get the path and substring the 'file:' from the URI
        String dockerfile = LUtil.class.getClassLoader().getResource("docker/loadTest").toString().substring(5);

        ProcessBuilder processBuilder = new ProcessBuilder("docker", "rmi", "-f", "vauvenal5/loadtest");
        processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
        Process docker = processBuilder.start();

        docker.waitFor();

        processBuilder = new ProcessBuilder("docker", "build", "-t", "vauvenal5/loadtest", dockerfile);
        processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
        Process proc = processBuilder.start();
        return proc.waitFor() == 0;
    }
    return true;
}

From source file:ai.eve.volley.stack.HurlStack.java

private static void setConnectionParametersForRequest(HttpURLConnection connection, Request<?> request)
        throws IOException, AuthFailureError {
    switch (request.getMethod()) {
    case Method.GET:
        // Not necessary to set the request method because connection defaults to GET but
        // being explicit here.
        connection.setRequestMethod("GET");
        break;//from   w w  w  .j  av  a  2  s .c  o m
    case Method.DELETE:
        connection.setRequestMethod("DELETE");
        break;
    case Method.POST:
        connection.setRequestMethod("POST");
        addBodyIfExists(connection, request);
        break;
    case Method.PUT:
        connection.setRequestMethod("PUT");
        addBodyIfExists(connection, request);
        break;
    case Method.HEAD:
        connection.setRequestMethod("HEAD");
        break;
    case Method.OPTIONS:
        connection.setRequestMethod("OPTIONS");
        break;
    case Method.TRACE:
        connection.setRequestMethod("TRACE");
        break;
    case Method.PATCH:
        addBodyIfExists(connection, request);
        connection.setRequestMethod("PATCH");
        break;
    default:
        throw new IllegalStateException("Unknown method type.");
    }
}

From source file:circleplus.app.http.AbstractHttpApi.java

private static HttpURLConnection getHttpURLConnection(URL url, int requestMethod, boolean acceptJson)
        throws IOException {
    if (D)/*from  www. j  a v a2s . c  om*/
        Log.d(TAG, "execute method: " + requestMethod + " url: " + url.toString() + " accept JSON ?= "
                + acceptJson);

    String method;
    boolean isPost;
    switch (requestMethod) {
    case REQUEST_METHOD_GET:
        method = "GET";
        isPost = false;
        break;
    case REQUEST_METHOD_POST:
        method = "POST";
        isPost = true;
        break;
    default:
        method = "GET";
        isPost = false;
        break;
    }

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(TIMEOUT);
    conn.setConnectTimeout(TIMEOUT);
    conn.setRequestProperty("Content-Type", JSON_UTF8_CONTENT_TYPE);
    if (isPost && acceptJson) {
        conn.setRequestProperty("Accept", JSON_CONTENT_TYPE);
    }
    conn.setRequestMethod(method);
    /* setDoOutput(true) equals setRequestMethod("POST") */
    conn.setDoOutput(isPost);
    conn.setChunkedStreamingMode(0);
    // Starts the query
    conn.connect();

    return conn;
}

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

@Then("The server at \"([^\"]*)\" is down$")
public static void _the_server_at_is_down(String endpointUrl) {
    try {/*w  w  w.j  ava  2s .  c  om*/
        HttpURLConnection connection = (HttpURLConnection) new URL(endpointUrl).openConnection();
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        connection.setRequestMethod("GET");
        connection.getResponseCode();
        Assert.fail("the endpoint " + endpointUrl + " should not have been available");
    } catch (MalformedURLException e) {
        throw new AssertionError(e);
    } catch (IOException e) {
        // this is what we are hoping for..
    }

}

From source file:com.wx.kernel.util.HttpKit.java

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

    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 (Entry<String, String> entry : headers.entrySet())
            conn.setRequestProperty(entry.getKey(), entry.getValue());

    return conn;
}

From source file:Main.java

@TargetApi(Build.VERSION_CODES.KITKAT)
public static String net(String strUrl, Map<String, Object> params, String method) throws Exception {
    HttpURLConnection conn = null;
    BufferedReader reader = null;
    String rs = null;/*w  w  w .ja v a 2  s . c om*/
    try {
        StringBuffer sb = new StringBuffer();
        if (method == null || method.equals("GET")) {
            strUrl = strUrl + "?" + urlencode(params);
        }
        URL url = new URL(strUrl);
        conn = (HttpURLConnection) url.openConnection();
        if (method == null || method.equals("GET")) {
            conn.setRequestMethod("GET");
        } else {
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
        }
        conn.setRequestProperty("User-agent", userAgent);
        conn.setUseCaches(false);
        conn.setConnectTimeout(DEF_CONN_TIMEOUT);
        conn.setReadTimeout(DEF_READ_TIMEOUT);
        conn.setInstanceFollowRedirects(false);
        conn.connect();
        if (params != null && method.equals("POST")) {
            try (DataOutputStream out = new DataOutputStream(conn.getOutputStream())) {
                out.writeBytes(urlencode(params));
            }
        }
        InputStream is = conn.getInputStream();
        reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
        String strRead = null;
        while ((strRead = reader.readLine()) != null) {
            sb.append(strRead);
        }
        rs = sb.toString();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            reader.close();
        }
        if (conn != null) {
            conn.disconnect();
        }
    }
    return rs;
}