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:io.github.retz.web.JobRequestRouter.java

private static String fetchHTTP(String addr, int retry) throws MalformedURLException, IOException {
    LOG.debug("Fetching {}", addr);
    HttpURLConnection conn = null;
    try {// w  w  w .  ja  v  a2 s  .  co  m
        conn = (HttpURLConnection) new URL(addr).openConnection();
        conn.setRequestMethod("GET");
        conn.setDoOutput(true);
        LOG.debug(conn.getResponseMessage());

    } catch (MalformedURLException e) {
        LOG.error(e.toString());
        throw e;
    } catch (IOException e) {
        LOG.error(e.toString());
        throw e;
    }

    try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), UTF_8))) {
        StringBuilder builder = new StringBuilder();
        String line;
        do {
            line = reader.readLine();
            builder.append(line);
        } while (line != null);
        LOG.debug("Fetched {} bytes from {}", builder.toString().length(), addr);
        return builder.toString();

    } catch (FileNotFoundException e) {
        throw e;
    } catch (IOException e) {
        // Somehow this happens even HTTP was correct
        LOG.debug("Cannot fetch file {}: {}", addr, e.toString());
        // Just retry until your stack get stuck; thanks to SO:33340848
        // and to that crappy HttpURLConnection
        if (retry < 0) {
            LOG.error("Retry failed. Last error was: {}", e.toString());
            throw e;
        }
        return fetchHTTP(addr, retry - 1);
    } finally {
        conn.disconnect();
    }

}

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

public static Task createTask(Task t) throws IOException {
    String _url = getBaseUri().build().toString();
    URL url = new URL(_url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    // add request header
    conn.setRequestMethod(IRequest.POST);
    addRequestHeader(conn, false);/*from   w w w.  j a  va2 s. c o  m*/
    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 for Title
    jgen.writeStartObject();
    jgen.writeStringField(Keys.Task.TITLE, t.getTitle());
    jgen.writeStringField(Keys.Task.COMPLETED, Boolean.toString(t.getIsCompleted()));
    jgen.writeStringField(Keys.Task.DESC, t.getDescription());
    jgen.writeStringField(Keys.Task.DEADLINE, Long.toString(t.getEndTimeInMillis()));
    jgen.writeStringField(Keys.Task.DATE_CREATED, t.getDateCreated());
    jgen.writeStringField(Keys.Task.DATE_ASSIGNED, t.getDateAssigned());
    jgen.writeStringField(Keys.Task.CRITERIA, t.getCompletionCriteria());
    jgen.writeStringField(Keys.Task.ASSIGNED_TO, t.getAssignedTo());
    jgen.writeStringField(Keys.Task.ASSIGNED_FROM, t.getAssignedFrom());
    jgen.writeStringField(Keys.Task.CREATED_BY, t.getCreatedBy());
    jgen.writeEndObject();
    jgen.close();

    String payload = json.toString("UTF8");
    ps.close();
    // Get server response
    sendPostPayload(conn, payload);
    String response = getServerResponse(conn);
    Map<String, String> responseMap = new HashMap<String, String>();
    if (responseMap.containsKey(Keys.Task.ID)) {
        t.setID(responseMap.get(Keys.Task.ID));
    }
    return t;
}

From source file:fr.free.movierenamer.utils.URIRequest.java

public static int getResponseCode(URL url, RequestProperty... properties) {
    try {/*from ww  w  .  j a va 2s.  co  m*/
        HttpURLConnection huc = (HttpURLConnection) openConnection(url.toURI(), properties);
        huc.setRequestMethod("GET");
        huc.connect();
        return huc.getResponseCode();
    } catch (Exception ex) {
        return 0;
    }
}

From source file:fr.lissi.belilif.om2m.rest.WebServiceActions.java

/**
 * Checks if a resource is reachable./*from  ww w  .  ja v  a 2 s .com*/
 *
 * @param uri the uri
 * @return true, if is reachable
 */
public static boolean isReachable(String uri) {
    try {
        HttpURLConnection.setFollowRedirects(false);
        HttpURLConnection myURLConnection = (HttpURLConnection) new URL(uri).openConnection();
        myURLConnection.setRequestMethod("HEAD");
        return (myURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK);
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

From source file:com.uk_postcodes.api.Postcode.java

/**
 * Get the postcode closest to the location.
 * @param location The device's location
 * @return the closest postcode/*w  ww .  j  a  v  a  2s  . c  o  m*/
 * @throws Exception
 */
public static String forLocation(Location location) throws Exception {
    String address = String.format(CALL, location.getLatitude(), location.getLongitude());

    Log.d("Postcode", "Calling: " + address);

    URL callUrl = new URL(address);
    HttpURLConnection callConnection = (HttpURLConnection) callUrl.openConnection();
    // The ten-second rule:
    // If there's no data in 10s (or TIMEOUT), assume the worst.
    callConnection.setReadTimeout(10000);
    // Set the request method to GET.
    callConnection.setRequestMethod("GET");
    int code = callConnection.getResponseCode();
    if (code != HttpURLConnection.HTTP_OK) {
        throw new Exception("A non-200 code was returned: " + code);
    }

    String responseStr;
    responseStr = IOUtils.toString(callConnection.getInputStream());
    callConnection.disconnect();

    JsonParser jp = new JsonParser();
    JsonElement response = jp.parse(responseStr);
    return response.getAsJsonObject().get("postcode").getAsString();
}

From source file:io.hops.hopsworks.api.tensorflow.TensorboardProxyServlet.java

public static String getHTML(String urlToRead) throws Exception {
    StringBuilder result = new StringBuilder();
    URL url = new URL(urlToRead);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;/*  ww  w.j av  a 2  s  .  c  o m*/
    while ((line = rd.readLine()) != null) {
        result.append(line);
    }
    rd.close();
    conn.disconnect();
    return result.toString();
}

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

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

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

    // 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:org.kymjs.kjframe.http.HttpConnectStack.java

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

From source file:com.nit.vicky.web.HttpFetcher.java

public static String downloadFileToSdCardMethod(String UrlToFile, Context context, String prefix, String method,
        Boolean isMP3) {/*from ww  w .j a va  2  s. c  o m*/
    try {
        URL url = new URL(UrlToFile);

        String extension = ".mp3";

        if (!isMP3)
            extension = UrlToFile.substring(UrlToFile.lastIndexOf("."));

        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setConnectTimeout(10 * 1000);
        urlConnection.setReadTimeout(10 * 1000);
        urlConnection.setRequestMethod(method);
        //urlConnection.setRequestProperty("Referer", "http://mm.taobao.com/");
        urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) ");
        urlConnection.setRequestProperty("Accept", "*/*");
        urlConnection.connect();

        File file = File.createTempFile(prefix, extension, DiskUtil.getStoringDirectory());

        FileOutputStream fileOutput = new FileOutputStream(file);
        InputStream inputStream = urlConnection.getInputStream();

        byte[] buffer = new byte[1024];
        int bufferLength = 0;

        while ((bufferLength = inputStream.read(buffer)) > 0) {
            fileOutput.write(buffer, 0, bufferLength);
        }
        fileOutput.close();

        return file.getAbsolutePath();

    } catch (Exception e) {
        return "FAILED " + e.getMessage();
    }
}

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

/**
 * Check if specified dataset already exists on server
 * /*w w w .j a  v  a 2s.  c  o m*/
 * @param dataSetName
 * @return boolean true if the dataset already exits, false if not
 * @throws IOException
 * @throws HttpException
 */
public static boolean chechIfExist(String dataSetName) throws IOException, HttpException {
    boolean exists = false;
    URL url = new URL(HOST + "/$/datasets/" + dataSetName);
    final HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
    httpConnection.setUseCaches(false);
    httpConnection.setRequestMethod("GET");

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

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