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.grosscommerce.ICEcat.utilities.Downloader.java

private static HttpURLConnection prepareConnection(String urlFrom, String login, String pwd)
        throws ProtocolException, IOException, MalformedURLException {
    URL url = new URL(urlFrom);
    HttpURLConnection uc = (HttpURLConnection) url.openConnection();
    // set up url connection to get retrieve information back
    uc.setRequestMethod("GET");
    uc.setDoInput(true);/*from  www .  j  a  v a2s  . com*/
    String val = (new StringBuffer(login).append(":").append(pwd)).toString();
    byte[] base = val.getBytes();
    String authorizationString = "Basic " + Base64.encodeBase64String(base);
    uc.setRequestProperty("Authorization", authorizationString);
    uc.setRequestProperty("Accept-Encoding", "gzip, xml");
    return uc;
}

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

protected static String updateHelper(String jsonPayload) throws IOException {
    // Server URL setup
    String _url = getBaseUri().build().toString();

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

    // add request header
    conn.setRequestMethod(IRequest.PUT);
    addRequestHeader(conn, true);//from  w  ww .  j a  v a2s.c  o  m

    int responseCode = sendPostPayload(conn, jsonPayload);
    String response = getServerResponse(conn);
    conn.disconnect();
    return response;
}

From source file:Main.java

/**
 * Do an HTTP POST and return the data as a byte array.
 *///  w w w. j a  v  a2s .  co m
public static byte[] executePost(String url, byte[] data, Map<String, String> requestProperties)
        throws MalformedURLException, IOException {
    HttpURLConnection urlConnection = null;
    try {
        urlConnection = (HttpURLConnection) new URL(url).openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoOutput(data != null);
        urlConnection.setDoInput(true);
        if (requestProperties != null) {
            for (Map.Entry<String, String> requestProperty : requestProperties.entrySet()) {
                urlConnection.setRequestProperty(requestProperty.getKey(), requestProperty.getValue());
            }
        }
        if (data != null) {
            OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
            out.write(data);
            out.close();
        }
        InputStream in = new BufferedInputStream(urlConnection.getInputStream());
        return convertInputStreamToByteArray(in);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

From source file:cc.vileda.sipgatesync.api.SipgateApi.java

@NonNull
private static String getUrl(final String apiUrl, final String token) throws IOException {
    final HttpURLConnection urlConnection = getConnection(apiUrl);
    urlConnection.setDoInput(true);//from   w  w  w . j  a va  2s.  c o m
    urlConnection.setRequestMethod("GET");
    if (token != null) {
        urlConnection.setRequestProperty("Authorization", "Bearer " + token);
    }
    StringBuilder sb = new StringBuilder();
    int HttpResult = urlConnection.getResponseCode();
    if (HttpResult == HttpURLConnection.HTTP_OK) {
        BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "utf-8"));
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line).append("\n");
        }
        br.close();

        return sb.toString();
    } else {
        System.out.println(urlConnection.getResponseMessage());
    }

    return "";
}

From source file:dk.nsi.minlog.test.utils.TestHelper.java

public static String sendRequest(String url, String action, String docXml, boolean failOnError)
        throws IOException, ServiceException {
    URL u = new URL(url);
    HttpURLConnection uc = (HttpURLConnection) u.openConnection();
    uc.setDoOutput(true);//from ww w.  j  a  v  a 2s  .  c o m
    uc.setDoInput(true);
    uc.setRequestMethod("POST");
    uc.setRequestProperty("SOAPAction", "\"" + action + "\"");
    uc.setRequestProperty("Content-Type", "text/xml; charset=utf-8;");
    OutputStream os = uc.getOutputStream();

    IOUtils.write(docXml, os, "UTF-8");
    os.flush();
    os.close();

    InputStream is;
    if (uc.getResponseCode() != 200) {
        is = uc.getErrorStream();
    } else {
        is = uc.getInputStream();
    }
    String res = IOUtils.toString(is);

    is.close();
    if (uc.getResponseCode() != 200 && (uc.getResponseCode() != 500 || failOnError)) {
        throw new ServiceException(res);
    }
    uc.disconnect();

    return res;
}

From source file:com.ant.myteam.gcm.POST2GCM.java

public static void post(String apiKey, Content content) {

    try {/*from  www  . ja  v  a2  s.com*/

        // 1. URL
        URL url = new URL("https://android.googleapis.com/gcm/send");

        // 2. Open connection
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        // 3. Specify POST method
        conn.setRequestMethod("POST");

        // 4. Set the headers
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Authorization", "key=" + apiKey);

        conn.setDoOutput(true);

        // 5. Add JSON data into POST request body

        //`5.1 Use Jackson object mapper to convert Contnet object into JSON
        ObjectMapper mapper = new ObjectMapper();

        // 5.2 Get connection output stream
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());

        // 5.3 Copy Content "JSON" into
        mapper.writeValue(wr, content);

        // 5.4 Send the request
        wr.flush();

        // 5.5 close
        wr.close();

        // 6. Get the response
        int responseCode = conn.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);

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

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

        // 7. Print result
        System.out.println(response.toString());

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:Main.java

public static boolean isConnectionAvailable() {
    class NetworkCheckTask extends AsyncTask<Void, Void, Boolean> {

        @Override//from   ww  w .  j  a  v a  2  s . co m
        protected Boolean doInBackground(Void... params) {
            try {
                URL url = new URL(MAD_SERVER + "/sync.html");
                HttpURLConnection conn = null;
                conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(999);
                conn.setRequestMethod("GET");
                conn.setDoInput(true);
                conn.connect();
                if (conn.getResponseCode() == 200)
                    return true;
                else
                    return false;
            } catch (Exception e) {
                return false;
            }
        }

    }

    try {
        NetworkCheckTask async = new NetworkCheckTask();
        async.execute();
        return async.get();
    } catch (Exception e) {
        return false;
    }
}

From source file:Main.java

public static String deleteUrl(String url, Bundle params) throws MalformedURLException, IOException {
    System.setProperty("http.keepAlive", "false");
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " agent");
    conn.setRequestMethod("DELETE");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setDoOutput(false);//from  w  ww .ja v a  2  s.  c  o m
    conn.setDoInput(true);
    //conn.setRequestProperty("Connection", "Keep-Alive");
    conn.connect();

    String response = "";
    try {
        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        // Error Stream contains JSON that we can parse to a FB error
        response = read(conn.getErrorStream());
    }
    return response;
}

From source file:pushandroid.POST2GCM.java

public static void post(Content content) {

    try {// www.  j av  a 2  s.  c  o  m

        // 1. URL
        URL url = new URL(URL);

        // 2. Open connection
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        // 3. Specify POST method
        conn.setRequestMethod("POST");

        // 4. Set the headers
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Authorization", "key=" + apiKey);

        conn.setDoOutput(true);

        // 5. Add JSON data into POST request body
        //`5.1 Use Jackson object mapper to convert Contnet object into JSON
        ObjectMapper mapper = new ObjectMapper();

        // 5.2 Get connection output stream
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());

        // 5.3 Copy Content "JSON" into
        mapper.writeValue(wr, content);

        // 5.4 Send the request
        wr.flush();

        // 5.5 close
        wr.close();

        // 6. Get the response
        int responseCode = conn.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

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

        // 7. Print result
        System.out.println(response.toString());

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:ilearnrw.utils.ServerHelperClass.java

public static String sendPost(String link, String urlParameters) throws Exception {
    String url = baseUrl + link;//from w  ww . ja  v a2 s.com

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    con.setRequestMethod("POST");
    con.setRequestProperty("Authorization", userNamePasswordBase64("api", "api"));

    con.setRequestProperty("Content-Type", "application/json;charset=utf-8");
    con.setDoOutput(true);
    OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream(), "UTF8");

    wr.write(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(), "UTF-8"));
    String inputLine;
    StringBuffer response = new StringBuffer();

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

    return response.toString();
}