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:fr.lissi.belilif.om2m.rest.WebServiceActions.java

/**
 * Checks if is reachable.// w  w  w  .j  a  v  a2s  .co m
 *
 * @param uri the uri
 * @param headers the headers
 * @return true, if is reachable
 */
public static boolean isReachable(String uri, HashMap<String, String> headers) {
    try {
        HttpURLConnection.setFollowRedirects(false);
        // note : you may also need
        // HttpURLConnection.setInstanceFollowRedirects(false)
        HttpURLConnection myURLConnection = (HttpURLConnection) new URL(uri).openConnection();
        myURLConnection.setRequestMethod("HEAD");
        for (String key : headers.keySet()) {
            myURLConnection.setRequestProperty("Authorization", headers.get(key));
        }
        LOGGER.info(myURLConnection.getResponseCode() + " / " + myURLConnection.toString());
        return (myURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK);
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

From source file:lu.list.itis.dkd.aig.util.FusekiHttpHelper.java

/**
 * Create a new dataset/*from  w  w w .j a v  a 2  s.c o m*/
 * 
 * @param dataSetName
 * @throws IOException
 * @throws HttpException
 */
public static void createDataSet(@NonNull String dataSetName) throws IOException, HttpException {
    logger.info("create dataset: " + dataSetName);

    URL url = new URL(HOST + "/$/datasets");
    final HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
    httpConnection.setUseCaches(false);
    httpConnection.setRequestMethod("POST");
    httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    // set content
    httpConnection.setDoOutput(true);
    final OutputStreamWriter out = new OutputStreamWriter(httpConnection.getOutputStream());
    out.write("dbName=" + URLEncoder.encode(dataSetName, "UTF-8") + "&dbType=mem");
    out.close();

    // handle HTTP/HTTPS strange behaviour
    httpConnection.connect();
    httpConnection.disconnect();

    // handle response
    switch (httpConnection.getResponseCode()) {
    case HttpURLConnection.HTTP_OK:
        break;
    default:
        throw new HttpException(
                httpConnection.getResponseCode() + " message: " + httpConnection.getResponseMessage());
    }
}

From source file:Main.java

/**
 * Issue a POST request to the server.//  w  ww .  j  ava 2  s . co m
 *
 * @param endpoint
 *            POST address.
 * @param params
 *            request parameters.
 *
 * @throws java.io.IOException
 *             propagated from POST.
 */
public static String post(String endpoint, Map<String, String> params) throws IOException {
    URL url;
    try {
        url = new URL(endpoint);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + endpoint);
    }
    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();
    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", "application/x-www-form-urlencoded;charset=UTF-8");
        // 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);
        }

        // Get Response
        InputStream is = conn.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\n');
        }
        rd.close();
        return response.toString();

    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:Main.java

/**
 * Issue a POST request to the server.//from  ww w.  jav a 2 s . co m
 *
 * @param endpoint
 *            POST address.
 * @param params
 *            request parameters.
 *
 * @throws IOException
 *             propagated from POST.
 */
public static String post_t(String endpoint, Map<String, Object> params, String contentType)
        throws IOException {
    URL url;
    try {
        url = new URL(endpoint);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + endpoint);
    }
    StringBuilder bodyBuilder = new StringBuilder();
    Iterator<Entry<String, Object>> iterator = params.entrySet().iterator();
    // constructs the POST body using the parameters
    while (iterator.hasNext()) {
        Entry<String, Object> param = iterator.next();
        bodyBuilder.append(param.getKey()).append('=').append(param.getValue());
        if (iterator.hasNext()) {
            bodyBuilder.append('&');
        }
    }
    String body = bodyBuilder.toString();
    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);
        }

        // Get Response
        InputStream is = conn.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\n');
        }
        rd.close();
        return response.toString();

    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:com.openforevent.main.UserPosition.java

public static Map<String, Object> userLocationProperties(DispatchContext ctx,
        Map<String, ? extends Object> context) throws IOException {
    Delegator delegator = ctx.getDelegator();
    LocalDispatcher dispatcher = ctx.getDispatcher();
    String visitId = (String) context.get("visitId");

    if (Debug.infoOn()) {
        Debug.logInfo("In userLocationProperties", module);
    }//from ww  w. jav  a 2 s .  c  om

    // get user coords
    coordsOfUserPosition(ctx, context);

    URL url = new URL(
            "https://graph.facebook.com/search?since=now&limit=4&q=2012-05-07&type=event&access_token="
                    + "AAACEdEose0cBAN9CB2ErxVN3JvK2gsrLslPt6e6Y7hJ0OrMEkMoyNwvHgSZCAEu2lCHZALlVWXZCW5JL8asMWoaPN3UAXFpZBsJJ6SvXRAAIZAXeTo0fD");
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

    // Set properties of the connection
    urlConnection.setRequestMethod("GET");
    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(true);
    urlConnection.setUseCaches(false);
    urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    // Retrieve the output
    int responseCode = urlConnection.getResponseCode();
    InputStream inputStream;
    if (responseCode == HttpURLConnection.HTTP_OK) {
        inputStream = urlConnection.getInputStream();
    } else {
        inputStream = urlConnection.getErrorStream();
    }

    StringWriter writer = new StringWriter();
    IOUtils.copy(inputStream, writer, "UTF-8");
    String theString = writer.toString();

    Debug.logInfo("Facebook stream = ", theString);

    if (theString.contains("AuthException") == true) {
        url = new URL("https://graph.facebook.com/oauth/access_token?" + "client_id=   283576871735609&"
                + "client_secret=   5cf1fe4e531dff8de228bfac61b8fdfa&" + "grant_type=fb_exchange_token&"
                + "fb_exchange_token="
                + "AAACEdEose0cBAN9CB2ErxVN3JvK2gsrLslPt6e6Y7hJ0OrMEkMoyNwvHgSZCAEu2lCHZALlVWXZCW5JL8asMWoaPN3UAXFpZBsJJ6SvXRAAIZAXeTo0fD");

        HttpURLConnection urlConnection1 = (HttpURLConnection) url.openConnection();

        // Set properties of the connection
        urlConnection1.setRequestMethod("GET");
        urlConnection1.setDoInput(true);
        urlConnection1.setDoOutput(true);
        urlConnection1.setUseCaches(false);
        urlConnection1.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        // Retrieve the output
        int responseCode1 = urlConnection1.getResponseCode();
        InputStream inputStream1;
        if (responseCode == HttpURLConnection.HTTP_OK) {
            inputStream1 = urlConnection1.getInputStream();
        } else {
            inputStream1 = urlConnection1.getErrorStream();
        }

        StringWriter writer1 = new StringWriter();
        IOUtils.copy(inputStream1, writer1, "UTF-8");
        String theString1 = writer1.toString();

        Debug.logInfo("Facebook stream1 = ", theString1);

    }

    Map<String, Object> paramOut = FastMap.newInstance();
    paramOut.put("geoName", "aaa");
    paramOut.put("abbreviation", "bbb");
    return paramOut;

}

From source file:net.cbtltd.server.WebService.java

/**
 * Gets the connection to the JSON server.
 *
 * @param url the connection URL.//from  w  w w .  j a  v a2s  . c  om
 * @param rq the request object.
 * @return the JSON string returned by the message.
 * @throws Throwable the exception thrown by the method.
 */
private static final String getConnection(URL url, String rq) throws Throwable {
    String jsonString = "";
    HttpURLConnection connection = null;
    try {
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        //connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json");

        if (rq != null) {
            connection.setRequestProperty("Accept", "application/json");
            connection.connect();
            byte[] outputBytes = rq.getBytes("UTF-8");
            OutputStream os = connection.getOutputStream();
            os.write(outputBytes);
        }

        if (connection.getResponseCode() != 200) {
            throw new RuntimeException("HTTP:" + connection.getResponseCode() + "URL " + url);
        }
        BufferedReader br = new BufferedReader(new InputStreamReader((connection.getInputStream())));
        String line;
        while ((line = br.readLine()) != null) {
            jsonString += line;
        }
    } catch (Throwable x) {
        throw new RuntimeException(x.getMessage());
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
    return jsonString;
}

From source file:com.linkedin.pinot.controller.helix.ControllerTest.java

public static String sendDeleteRequest(String urlString) throws IOException {
    final long start = System.currentTimeMillis();

    final URL url = new URL(urlString);
    final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);//from  w ww  .jav a 2 s . c o  m
    conn.setRequestMethod("DELETE");
    conn.connect();

    final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

    final StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }

    final long stop = System.currentTimeMillis();

    LOGGER.info(" Time take for Request : " + urlString + " in ms:" + (stop - start));

    return sb.toString();
}

From source file:Main.java

public static String uploadFile(File file, String RequestURL) {
    String BOUNDARY = UUID.randomUUID().toString();
    String PREFIX = "--", LINE_END = "\r\n";
    String CONTENT_TYPE = "multipart/form-data";

    try {/*  w w  w.  j a v a2  s.co m*/
        URL url = new URL(RequestURL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(TIME_OUT);
        conn.setConnectTimeout(TIME_OUT);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Charset", CHARSET);
        conn.setRequestProperty("connection", "keep-alive");
        conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
        if (file != null) {

            OutputStream outputSteam = conn.getOutputStream();

            DataOutputStream dos = new DataOutputStream(outputSteam);
            StringBuffer sb = new StringBuffer();
            sb.append(PREFIX);
            sb.append(BOUNDARY);
            sb.append(LINE_END);

            sb.append("Content-Disposition: form-data; name=\"img\"; filename=\"" + file.getName() + "\""
                    + LINE_END);
            sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END);
            sb.append(LINE_END);
            dos.write(sb.toString().getBytes());
            InputStream is = new FileInputStream(file);
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = is.read(bytes)) != -1) {
                dos.write(bytes, 0, len);
            }
            is.close();
            dos.write(LINE_END.getBytes());
            byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
            dos.write(end_data);
            dos.flush();

            int res = conn.getResponseCode();
            Log.e(TAG, "response code:" + res);
            if (res == 200) {
                return SUCCESS;
            }
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return FAILURE;
}

From source file:Main.java

public static String getResponse(String urlParam) {
    try {//from  w w w .java 2s  .  c o  m
        URL url = new URL(urlParam);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE6.0; Windows NT 5.1; SV1)");
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("GET");
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            InputStream inputStream = conn.getInputStream();
            return inputStream2String(inputStream);
        }
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
    return null;
}

From source file:com.scut.easyfe.network.kjFrame.http.HttpConnectStack.java

static void setConnectionParametersForRequest(HttpURLConnection connection, Request<?> request)
        throws IOException {
    switch (request.getMethod()) {
    case Request.HttpMethod.GET:
        connection.setRequestMethod("GET");
        break;// www. j a  v a  2s.com
    case Request.HttpMethod.DELETE:
        connection.setRequestMethod("DELETE");
        break;
    case Request.HttpMethod.POST:
        connection.setRequestMethod("POST");
        addBodyIfExists(connection, request);
        break;
    case Request.HttpMethod.PUT:
        connection.setRequestMethod("PUT");
        addBodyIfExists(connection, request);
        break;
    case Request.HttpMethod.HEAD:
        connection.setRequestMethod("HEAD");
        break;
    case Request.HttpMethod.OPTIONS:
        connection.setRequestMethod("OPTIONS");
        break;
    case Request.HttpMethod.TRACE:
        connection.setRequestMethod("TRACE");
        break;
    case Request.HttpMethod.PATCH:
        connection.setRequestMethod("PATCH");
        addBodyIfExists(connection, request);
        break;
    default:
        throw new IllegalStateException("Unknown method type.");
    }
}