Example usage for java.net HttpURLConnection HTTP_OK

List of usage examples for java.net HttpURLConnection HTTP_OK

Introduction

In this page you can find the example usage for java.net HttpURLConnection HTTP_OK.

Prototype

int HTTP_OK

To view the source code for java.net HttpURLConnection HTTP_OK.

Click Source Link

Document

HTTP Status-Code 200: OK.

Usage

From source file:nz.skytv.example.SwaggerApplication.java

@ApiOperation(value = "Delete a books", notes = "Delete a book.", response = Book.class, tags = { "book" })
@ApiResponses({ @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Book deleted successfully"),
        @ApiResponse(code = HttpURLConnection.HTTP_GONE, message = "Not found") })
@RequestMapping(value = { "/rest/book" }, method = RequestMethod.DELETE)
void deleteBook(@ApiParam(value = "Book isbn", required = true) @RequestParam("isbn") final String isbn) {
    LOG.debug("delete {}", isbn);
}

From source file:com.impetus.ankush.agent.utils.AgentRestClient.java

/**
 * Method sendNodeInfo./*from  www. jav  a 2 s.  c  o m*/
 * 
 * @param urlPath
 *            String
 * @param input
 *            String
 * @return String
 * @throws IOException
 */
private String sendRequest(String urlPath, String input, String method, String accept, String contentType) {
    HttpURLConnection conn = null;
    OutputStream os = null;
    BufferedReader br = null;
    InputStreamReader isr = null;

    try {
        LOGGER.info("URL Path : " + urlPath);
        URL url = new URL(urlPath);

        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod(method);
        conn.setRequestProperty("Accept", accept);
        conn.setRequestProperty("Content-type", contentType);

        if (input != null && !input.isEmpty()) {
            os = conn.getOutputStream();
            os.write(input.getBytes());
            os.flush();
        }

        LOGGER.info("Response Code :" + conn.getResponseCode());

        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
        }
        isr = new InputStreamReader(conn.getInputStream());
        br = new BufferedReader(isr);

        String buffer = "";
        StringBuilder output = new StringBuilder();
        while ((buffer = br.readLine()) != null) {
            output.append(buffer);
        }
        return output.toString();
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        return null;
    } finally {
        try {
            if (isr != null) {
                isr.close();
            }

            if (br != null) {
                br.close();
            }
        } catch (Exception e) {
            LOGGER.error("Unable to close buffer stream while sending request", e);
        }
        if (conn != null) {
            conn.disconnect();
        }

        if (os != null) {
            IOUtils.closeQuietly(os);
        }
    }
}

From source file:com.canoo.cog.sonar.SonarService.java

String callSonarAuth(String path, String userName, String password) throws SonarException {
    URL url;//from   ww  w .  j a v a2  s  .com
    try {
        url = new URL(baseUrl + path);
    } catch (MalformedURLException e) {
        throw new SonarException("Error in Calling Sonar Service.", e);
    }

    try {
        String authPropertyKey;
        HttpURLConnection connection;
        String encoding = new String(Base64.encodeBase64((userName + ":" + password).getBytes()));

        if (isProxyUsed()) {
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("webproxy.balgroupit.com", 3128));
            authPropertyKey = "Proxy-Authorization";
            connection = (HttpURLConnection) url.openConnection(proxy);
        } else {
            authPropertyKey = "Authorization";
            connection = (HttpURLConnection) url.openConnection();
        }

        connection.setRequestMethod("GET");
        connection.setDoOutput(true);
        connection.setRequestProperty(authPropertyKey, "Basic " + encoding);
        InputStream content = connection.getInputStream();
        BufferedReader in = new BufferedReader(new InputStreamReader(content));

        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new SonarException("HTTP Get call to " + url.getPath() + " was not successful.");
        }

        return IOUtils.toString(in);
    } catch (ProtocolException e) {
        throw new SonarException("Error in Calling Sonar Service.", e);
    } catch (IOException e) {
        throw new SonarException("Error in Calling Sonar Service.", e);
    }
}

From source file:net.andylizi.colormotd.anim.updater.Updater.java

private boolean checkUpdate() {
    if (new File(Bukkit.getUpdateFolderFile(), fileName).exists()) {
        cancel();/*from   ww  w .  j ava  2  s .c om*/
    }
    URL url;
    try {
        url = new URL(UPDATE_URL);
    } catch (MalformedURLException ex) {
        if (DEBUG) {
            ex.printStackTrace();
        }
        return false;
    }
    try {
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setUseCaches(false);
        conn.setRequestMethod("GET");
        conn.addRequestProperty("User-Agent", USER_AGENT);
        if (etag != null) {
            conn.addRequestProperty("If-None-Match", etag);
        }
        conn.addRequestProperty("Accept", "application/json,text/plain,*/*;charset=utf-8");
        conn.addRequestProperty("Accept-Encoding", "gzip");
        conn.addRequestProperty("Cache-Control", "no-cache");
        conn.addRequestProperty("Date", new Date().toString());
        conn.addRequestProperty("Connection", "close");

        conn.setDoInput(true);
        conn.setDoOutput(false);
        conn.setConnectTimeout(2000);
        conn.setReadTimeout(2000);

        conn.connect();

        if (conn.getHeaderField("ETag") != null) {
            etag = conn.getHeaderField("ETag");
        }
        if (DEBUG) {
            logger.log(Level.INFO, "DEBUG ResponseCode: {0}", conn.getResponseCode());
            logger.log(Level.INFO, "DEBUG ETag: {0}", etag);
        }
        if (conn.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
            return false;
        } else if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            return false;
        }

        BufferedReader input = null;
        if (conn.getContentEncoding() != null && conn.getContentEncoding().contains("gzip")) {
            input = new BufferedReader(
                    new InputStreamReader(new GZIPInputStream(conn.getInputStream()), "UTF-8"), 1);
        } else {
            input = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"), 1);
        }

        StringBuilder builder = new StringBuilder();
        String buffer = null;
        while ((buffer = input.readLine()) != null) {
            builder.append(buffer);
        }
        try {
            JSONObject jsonObj = (JSONObject) new JSONParser().parse(builder.toString());
            int build = ((Number) jsonObj.get("build")).intValue();
            if (build <= buildVersion) {
                return false;
            }
            String version = (String) jsonObj.get("version");
            String msg = (String) jsonObj.get("msg");
            String download_url = (String) jsonObj.get("url");
            newVersion = new NewVersion(version, build, msg, download_url);
            return true;
        } catch (ParseException ex) {
            if (DEBUG) {
                ex.printStackTrace();
            }
            exception = ex;
            return false;
        }
    } catch (SocketTimeoutException ex) {
        return false;
    } catch (IOException ex) {
        if (DEBUG) {
            ex.printStackTrace();
        }
        exception = ex;
        return false;
    }
}

From source file:com.stackmob.customcode.HelloWorld.java

@Override
public ResponseToProcess execute(ProcessedAPIRequest request, SDKServiceProvider serviceProvider) {
    Map<String, Object> map = new HashMap<String, Object>();

    String accessToken = "";
    JSONParser parser = new JSONParser();
    try {/* w w  w .ja v  a  2  s  . c o m*/
        Object obj = parser.parse(request.getBody());
        JSONObject jsonObject = (JSONObject) obj;
        accessToken = (String) jsonObject.get("accessToken");
    } catch (ParseException pe) {

    }

    String token = "CAAGF19ZAX3kUBAGbJyqQntgfQa7thZBDtMyhNVTpX5ZCpGXzBuDJQogJjVCjJZBq0DoZCCo8vqNOaFPEwMvJm7ZBZAeDogCA6ZCMsYSfSvAKa8QYUNcouRUNAOaiYZC6ZBpCeXaNfJOqVyi8fMT4D69odGdF6YlTh5Oays8coEVEQq3tyMzLok7urPlhpNmwW0ZBWNkMLF3AwDxIQZDZD";
    LoggerService logger = serviceProvider.getLoggerService("logger");
    //      String urlMe = "https://graph.facebook.com/me?access_token=" + token;
    //      String urlFriends = "https://graph.facebook.com/me/friends?access_token=" + token;
    //
    //      // Formulate request headers
    //      Header accept = new Header("Accept-Charset", "utf-8");
    //      Header content = new Header("Content-Type", "application/x-www-form-urlencoded");
    //
    //      Set<Header> set = new HashSet();
    //      set.add(accept);
    //      set.add(content);
    //
    //      String responseBodyMe = "";
    //      String responseBodyFriends = "";
    logger.error("heeeeeeeeeeeeeh");
    try {
        FacebookClient facebookClient = new DefaultFacebookClient(token, serviceProvider);
    } catch (Exception e) {
        logger.error(e.getMessage());

    }
    //      try {
    //          HttpService http = serviceProvider.getHttpService();
    //
    //      /* In this Example we are going to be making a GET request
    //       * but PUT/POST/DELETE requests are also possible.
    //       */
    //          GetRequest reqMe = new GetRequest(urlMe,set);
    //          HttpResponse respMe = http.get(reqMe);
    //
    //          GetRequest reqFriends = new GetRequest(urlFriends,set);
    //          HttpResponse respFriends = http.get(reqFriends);
    //
    //          responseBodyMe = respMe.getBody();
    //          responseBodyFriends = respFriends.getBody();
    //
    //
    //      } catch (Exception e) {}
    //
    //      map.put("me", responseBodyMe);
    //      map.put("friends", responseBodyFriends);
    map.put("friends", "hamada");

    return new ResponseToProcess(HttpURLConnection.HTTP_OK, map);
}

From source file:de.fu_berlin.inf.dpp.netbeans.feedback.FileSubmitter.java

/**
 * Tries to upload the given file to the given HTTP server (via POST
 * method)./* w  ww .jav  a  2  s .  co m*/
 * 
 * @param file
 *            the file to upload
 * @param url
 *            the URL of the server, that is supposed to handle the file
 * @param monitor
 *            a monitor to report progress to
 * @throws IOException
 *             if an I/O error occurs
 * 
 */

public static void uploadFile(final File file, final String url, IProgressMonitor monitor) throws IOException {

    final String CRLF = "\r\n";
    final String doubleDash = "--";
    final String boundary = generateBoundary();

    HttpURLConnection connection = null;
    OutputStream urlConnectionOut = null;
    FileInputStream fileIn = null;

    if (monitor == null)
        monitor = new NullProgressMonitor();

    int contentLength = (int) file.length();

    if (contentLength == 0) {
        log.warn("file size of file " + file.getAbsolutePath() + " is 0 or the file does not exist");
        return;
    }

    monitor.beginTask("Uploading file " + file.getName(), contentLength);

    try {
        URL connectionURL = new URL(url);

        if (!"http".equals(connectionURL.getProtocol()))
            throw new IOException("only HTTP protocol is supported");

        connection = (HttpURLConnection) connectionURL.openConnection();
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setReadTimeout(TIMEOUT);
        connection.setConnectTimeout(TIMEOUT);

        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

        String contentDispositionLine = "Content-Disposition: form-data; name=\"" + file.getName()
                + "\"; filename=\"" + file.getName() + "\"" + CRLF;

        String contentTypeLine = "Content-Type: application/octet-stream; charset=ISO-8859-1" + CRLF;

        String contentTransferEncoding = "Content-Transfer-Encoding: binary" + CRLF;

        contentLength += 2 * boundary.length() + contentDispositionLine.length() + contentTypeLine.length()
                + contentTransferEncoding.length() + 4 * CRLF.length() + 3 * doubleDash.length();

        connection.setFixedLengthStreamingMode(contentLength);

        connection.connect();

        urlConnectionOut = connection.getOutputStream();

        PrintWriter writer = new PrintWriter(new OutputStreamWriter(urlConnectionOut, "US-ASCII"), true);

        writer.append(doubleDash).append(boundary).append(CRLF);
        writer.append(contentDispositionLine);
        writer.append(contentTypeLine);
        writer.append(contentTransferEncoding);
        writer.append(CRLF);
        writer.flush();

        fileIn = new FileInputStream(file);
        byte[] buffer = new byte[8192];

        for (int read = 0; (read = fileIn.read(buffer)) > 0;) {
            if (monitor.isCanceled())
                return;

            urlConnectionOut.write(buffer, 0, read);
            monitor.worked(read);
        }

        urlConnectionOut.flush();

        writer.append(CRLF);
        writer.append(doubleDash).append(boundary).append(doubleDash).append(CRLF);
        writer.close();

        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            log.debug("uploaded file " + file.getAbsolutePath() + " to " + connectionURL.getHost());
            return;
        }

        throw new IOException("failed to upload file " + file.getAbsolutePath() + connectionURL.getHost() + " ["
                + connection.getResponseMessage() + "]");
    } finally {
        IOUtils.closeQuietly(fileIn);
        IOUtils.closeQuietly(urlConnectionOut);

        if (connection != null)
            connection.disconnect();

        monitor.done();
    }
}

From source file:com.andrious.btc.data.jsonUtils.java

private static HttpURLConnection urlConnect(String urlString) throws IOException {

    URL url = new URL(urlString);

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

    conn.setRequestMethod("GET");

    conn.setRequestProperty("Accept", "application/json");

    int response = conn.getResponseCode();

    if (response != HttpURLConnection.HTTP_OK) {

        if (!handleResponse(response, conn)) {

            throw new RuntimeException("Failed : HTTP error code : " + response);
        }//from w  w  w . j a v a 2 s  . co m
    }

    return conn;
}

From source file:com.andrew.apollo.cache.ImageFetcher.java

/**
 * Download a {@link Bitmap} from a URL, write it to a disk and return the
 * File pointer. This implementation uses a simple disk cache.
 *
 * @param context The context to use//from   w  ww  .jav a2  s .c  o  m
 * @param urlString The URL to fetch
 * @return A {@link File} pointing to the fetched bitmap
 */
public static final File downloadBitmapToFile(final Context context, final String urlString,
        final String uniqueName) {
    final File cacheDir = ImageCache.getDiskCacheDir(context, uniqueName);

    if (!cacheDir.exists()) {
        cacheDir.mkdir();
    }

    HttpURLConnection urlConnection = null;
    BufferedOutputStream out = null;

    try {
        final File tempFile = File.createTempFile("bitmap", null, cacheDir); //$NON-NLS-1$

        final URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        if (urlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            return null;
        }
        final InputStream in = new BufferedInputStream(urlConnection.getInputStream(), IO_BUFFER_SIZE_BYTES);
        out = new BufferedOutputStream(new FileOutputStream(tempFile), IO_BUFFER_SIZE_BYTES);

        int oneByte;
        while ((oneByte = in.read()) != -1) {
            out.write(oneByte);
        }
        return tempFile;
    } catch (final IOException ignored) {
        ignored.printStackTrace();
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (out != null) {
            try {
                out.close();
            } catch (final IOException ignored) {
            }
        }
    }
    return null;
}

From source file:com.binil.pushnotification.ServerUtil.java

/**
 * Issue a POST request to the server./*from   w w w .ja v a2 s. co m*/
 *
 * @param endpoint POST address.
 * @param params   request parameters.
 * @throws java.io.IOException propagated from POST.
 */
private static void post(String endpoint, Map<String, Object> params) throws IOException, JSONException {

    URL url = new URL(endpoint);
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setRequestMethod("POST");
    urlConnection.setRequestProperty("Cache-Control", "no-cache");
    urlConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
    urlConnection.setRequestProperty("Accept-Encoding", "gzip,deflate");
    urlConnection.setRequestProperty("Accept", "*/*");

    urlConnection.setDoOutput(true);

    JSONObject json = new JSONObject(params);
    String body = json.toString();
    urlConnection.setFixedLengthStreamingMode(body.length());

    try {
        OutputStream os = urlConnection.getOutputStream();
        os.write(body.getBytes("UTF-8"));
        os.close();

    } catch (Exception e) {
        e.printStackTrace();

    } finally {
        int status = urlConnection.getResponseCode();
        String connectionMsg = urlConnection.getResponseMessage();
        urlConnection.disconnect();

        if (status != HttpURLConnection.HTTP_OK) {
            Log.wtf(TAG, connectionMsg);
            throw new IOException("Post failed with error code " + status);
        }
    }

}

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

/**
 * Create a new dataset//  ww w  .  j av  a  2s . co 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());
    }
}