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.github.terma.m.node.Node.java

private static void send(final String serverHost, final int serverPort, final String context,
        final List<Event> events) throws IOException {
    final HttpURLConnection connection = (HttpURLConnection) new URL("http", serverHost, serverPort,
            context + "/node").openConnection();
    connection.setDoOutput(true);// w ww.  j  av a  2 s.com
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "text/json");
    connection.setRequestProperty("charset", "utf-8");
    connection.setUseCaches(false);
    connection.setInstanceFollowRedirects(false);
    connection.connect();
    OutputStream outputStream = connection.getOutputStream();
    outputStream.write(new Gson().toJson(events).getBytes());
    connection.getInputStream().read();
    outputStream.close();
}

From source file:com.teleca.jamendo.util.download.DownloadTask.java

public static Boolean downloadFile(DownloadJob job) throws IOException {

    // TODO rewrite to apache client

    PlaylistEntry mPlaylistEntry = job.getPlaylistEntry();
    String mDestination = job.getDestination();

    URL u = new URL(mPlaylistEntry.getTrack().getStream());
    HttpURLConnection c = (HttpURLConnection) u.openConnection();
    c.setRequestMethod("GET");
    c.setDoOutput(true);//  w  w w  .  j  a  va 2  s.  com
    c.connect();
    job.setTotalSize(c.getContentLength());

    Log.i(JamendoApplication.TAG, "creating file");

    String path = DownloadHelper.getAbsolutePath(mPlaylistEntry, mDestination);
    String fileName = DownloadHelper.getFileName(mPlaylistEntry, job.getFormat());

    try {
        // Create multiple directory
        boolean success = (new File(path)).mkdirs();
        if (success) {
            Log.i(JamendoApplication.TAG, "Directory: " + path + " created");
        }

    } catch (Exception e) {//Catch exception if any
        Log.e(JamendoApplication.TAG, "Error creating folder", e);
        return false;
    }

    FileOutputStream f = new FileOutputStream(new File(path, fileName));

    InputStream in = c.getInputStream();

    if (in == null) {
        // When InputStream is a NULL
        return false;
    }

    byte[] buffer = new byte[1024];
    int lenght = 0;
    while ((lenght = in.read(buffer)) > 0) {
        f.write(buffer, 0, lenght);
        job.setDownloadedSize(job.getDownloadedSize() + lenght);
    }

    f.close();

    downloadCover(job);
    return true;

}

From source file:Main.java

public static String callJsonAPI(String urlString) {
    // Use HttpURLConnection as per Android 6.0 spec, instead of less efficient HttpClient
    HttpURLConnection urlConnection = null;
    StringBuilder jsonResult = new StringBuilder();

    try {// w  w  w.jav a2 s.  co m
        URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setUseCaches(false);
        urlConnection.setConnectTimeout(TIMEOUT_CONNECTION);
        urlConnection.setReadTimeout(TIMEOUT_READ);
        urlConnection.connect();

        int status = urlConnection.getResponseCode();

        switch (status) {
        case 200:
        case 201:
            BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

            String line;
            while ((line = br.readLine()) != null) {
                jsonResult.append(line).append("\n");
            }
            br.close();
        }
    } catch (MalformedURLException e) {
        System.err.print(e.getMessage());
        return e.getMessage();
    } catch (IOException e) {
        System.err.print(e.getMessage());
        return e.getMessage();
    } finally {
        if (urlConnection != null) {
            try {
                urlConnection.disconnect();
            } catch (Exception e) {
                System.err.print(e.getMessage());
            }
        }
    }
    return jsonResult.toString();
}

From source file:flow.visibility.tapping.OpenDayLightUtils.java

/** The function for inserting the flow */

public static void FlowEntry(String ODPURL, String ODPAccount, String ODPPassword) throws Exception {

    //String user = "admin";
    //String password = "admin";
    String baseURL = "http://" + ODPURL + "/controller/nb/v2/flowprogrammer";
    String containerName = "default";

    /** Check the connection for ODP REST API */

    try {/* w w  w  .  j  av a  2  s .  c  om*/

        // Create URL = base URL + container
        URL url = new URL(baseURL + "/" + containerName);

        // Create authentication string and encode it to Base64
        String authStr = ODPAccount + ":" + ODPPassword;
        String encodedAuthStr = Base64.encodeBase64String(authStr.getBytes());

        // Create Http connection
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // Set connection properties
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Authorization", "Basic " + encodedAuthStr);
        connection.setRequestProperty("Accept", "application/json");

        // Get the response from connection's inputStream
        InputStream content = (InputStream) connection.getInputStream();

        /** The create the frame and blank pane */
        OpenDayLightUtils object = new OpenDayLightUtils();
        object.setVisible(true);

        /** Read the Flow entry in JSON Format */
        BufferedReader in = new BufferedReader(new InputStreamReader(content));
        String line = "";

        /** Print line by line in Pane with Pretty JSON */
        while ((line = in.readLine()) != null) {

            JSONParser jsonParser = new JSONParser();
            JSONObject jsonObject = (JSONObject) jsonParser.parse(line);

            Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
            String json = gson.toJson(jsonObject);
            System.out.println(json);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:io.github.retz.scheduler.MesosHTTPFetcher.java

private static Optional<String> fetchSlaveAddr(String master, String slaveId) {
    URL url;//w  w w .j  a  v a  2s.c o  m
    try {
        url = new URL("http://" + master + "/slaves");
    } catch (MalformedURLException e) {
        return Optional.empty();
    }
    HttpURLConnection conn;
    try {
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setDoOutput(true);
        return extractSlaveAddr(conn.getInputStream(), slaveId);
    } catch (IOException e) {
        return Optional.empty();
    }
}

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

public static Group createGroup(Group g) throws IOException, MalformedURLException {
    // Server URL setup
    String _url = getBaseUri().build().toString();

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

    conn.setRequestMethod("POST");
    addRequestHeader(conn, true);//from   w  w  w  .  j  av  a 2s  .  co m

    // prepare POST payload
    ByteArrayOutputStream json = new ByteArrayOutputStream();
    // this type of print stream allows us to get a string easily
    PrintStream ps = new PrintStream(json);
    // Create a generator to build the JSON string
    JsonGenerator jgen = JFACTORY.createGenerator(ps, JsonEncoding.UTF8);

    // Build JSON Object
    jgen.writeStartObject();
    jgen.writeStringField(Keys.Group.TITLE, g.getGroupTitle());
    jgen.writeArrayFieldStart(Keys.Group.MEMBERS);
    for (User member : g.getMembers()) {
        jgen.writeStartObject();
        jgen.writeStringField(Keys.User.ID, member.getID());
        jgen.writeEndObject();

    }
    jgen.writeEndArray();
    jgen.writeEndObject();
    jgen.close();

    // Get JSON Object payload from print stream
    String payload = json.toString("UTF8");
    ps.close();

    // send payload
    int responseCode = sendPostPayload(conn, payload);
    String response = getServerResponse(conn);

    // prepare to get the id of the created Meeting
    // Map<String, String> responseMap = new HashMap<String, String>();

    /*
     * result should get valid={"meetingID":"##"}
     */
    String result = new String();
    if (!response.isEmpty()) {
        // responseMap = MAPPER.readValue(response,
        // new TypeReference<HashMap<String, String>>() {
        // });
        JsonNode groupNode = MAPPER.readTree(response);
        if (!groupNode.has(Keys.Group.ID)) {
            result = "invalid";
        } else
            result = groupNode.get(Keys.Group.ID).asText();
    }

    if (!result.equalsIgnoreCase("invalid"))
        g.setID(result);

    conn.disconnect();
    return g;
}

From source file:Main.java

public static String customrequest(String url, HashMap<String, String> params, String method) {
    try {//from  w  w w.  ja va  2 s . c om

        URL postUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) postUrl.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setConnectTimeout(5 * 1000);

        conn.setRequestMethod(method);
        conn.setUseCaches(false);
        conn.setInstanceFollowRedirects(true);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)");

        conn.connect();
        OutputStream out = conn.getOutputStream();
        StringBuilder sb = new StringBuilder();
        if (null != params) {
            int i = params.size();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                if (i == 1) {
                    sb.append(entry.getKey() + "=" + entry.getValue());
                } else {
                    sb.append(entry.getKey() + "=" + entry.getValue() + "&");
                }

                i--;
            }
        }
        String content = sb.toString();
        out.write(content.getBytes("UTF-8"));
        out.flush();
        out.close();
        InputStream inStream = conn.getInputStream();
        String result = inputStream2String(inStream);
        conn.disconnect();
        return result;
    } catch (Exception e) {
        // TODO: handle exception
    }
    return null;
}

From source file:com.futureplatforms.kirin.internal.attic.IOUtils.java

public static InputStream postConnection(Context context, URL url, String method, String urlParameters)
        throws IOException {
    if (!url.getProtocol().startsWith("http")) {
        return url.openStream();
    }/*from   w w w . j a va  2 s.  c o m*/

    URLConnection c = url.openConnection();

    HttpURLConnection connection = (HttpURLConnection) c;

    connection.setRequestMethod(method.toUpperCase());
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
    connection.setRequestProperty("Content-Language", "en-US");

    connection.setUseCaches(false);
    connection.setDoInput(true);
    connection.setDoOutput(true);

    OutputStream output = null;
    try {
        output = connection.getOutputStream();
        output.write(urlParameters.getBytes("UTF-8"));
        output.flush();
    } finally {
        IOUtils.close(output);
    }
    return connection.getInputStream();
}

From source file:yodlee.ysl.api.io.HTTP.java

public static String doPostRegisterUser(String url, String registerParam, Map<String, String> cobTokens,
        boolean isEncodingNeeded) throws IOException {
    //String processedURL = url+"?registerParam="+registerParam;
    /* String registerUserJson="{"
    + "      \"user\" : {"//w ww.jav  a  2 s  .  c  o  m
    + "            \"loginName\" : \"TestT749\","
    + "            \"password\" : \"TESTT@123\","
    + "            \"email\" : \"testet@yodlee.com\","
    + "            \"firstName\" : \"Rehhsty\","
    + "            \"lastName\" :\"ysl\""
    +"             } ,"
            
    + "      \"preference\" : {"
    + "      \"address\" : {"
    + "            \"street\" : \"abcd\","
    + "            \"state\" : \"CA\","
    + "            \"city\" : \"RWS\","
    + "            \"postalCode\" : \"98405\","
    + "            \"countryIsoCode\" : \"USA\""
    +"             } ,"
    + "            \"currency\" : \"USD\","
    + "            \"timeZone\" : \"PST\","
    + "            \"dateFormat\" : \"MM/dd/yyyy\""
    + "}"
    + "}";*/

    //encoding url
    registerParam = java.net.URLEncoder.encode(registerParam, "UTF-8");
    String processedURL = url + "?registerParam=" + registerParam;
    String mn = "doIO(POST : " + processedURL + ", " + registerParam + "sessionTokens : " + " )";
    System.out.println(fqcn + " :: " + mn);
    URL restURL = new URL(processedURL);
    HttpURLConnection conn = (HttpURLConnection) restURL.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("User-Agent", userAgent);
    conn.setRequestProperty("Content-Type", contentTypeURLENCODED);
    conn.setRequestProperty("Content-Type", "text/plain;charset=UTF-8");
    conn.setRequestProperty("Authorization", cobTokens.toString());
    conn.setDoOutput(true);
    conn.setRequestProperty("Accept-Charset", "UTF-8");
    int responseCode = conn.getResponseCode();
    if (responseCode == 200) {
        System.out.println(fqcn + " :: " + mn + " : " + "Sending 'HTTP POST' request");
        System.out.println(fqcn + " :: " + mn + " : " + "Response Code : " + responseCode);
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuilder jsonResponse = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            jsonResponse.append(inputLine);
        }
        in.close();
        System.out.println(fqcn + " :: " + mn + " : " + jsonResponse.toString());
        return new String(jsonResponse);
    } else {
        System.out.println("Invalid input");
        return new String();

    }
}

From source file:RemoteDeviceDiscovery.java

public static void postDevice(RemoteDevice d) throws Exception {
    String url = "http://bluetoothdatabase.com/datacollection/";
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    //add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", "blucat");
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

    String urlParameters = deviceJson(d);

    // Send post request
    con.setDoOutput(true);/*from  w w  w. j av a 2 s. c o m*/
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();

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

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