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:org.gameontext.regsvc.RatingEndpoint.java

/**
 * POST /regsvc/v1/rate/* w  ww. ja v a2  s  .c  o m*/
 * @throws JsonProcessingException
 */
@POST
@ApiOperation(value = "Rate a registered room", notes = "Rate a room for a given event", code = HttpURLConnection.HTTP_OK)
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response rateRoom(@ApiParam(value = "Room to rate", required = true) Rating rating) {
    repo.createRating(rating);
    return Response.ok(rating).build();
}

From source file:org.dataone.proto.trove.mn.http.client.DataHttpClientHandler.java

public static synchronized String executePost(HttpClient httpclient, HttpPost httpPost)
        throws ServiceFailure, NotFound, InvalidToken, NotAuthorized, IdentifierNotUnique, UnsupportedType,
        InsufficientResources, InvalidSystemMetadata, NotImplemented, InvalidCredentials, InvalidRequest,
        AuthenticationTimeout, UnsupportedMetadataType, HttpException {
    String response = null;//from  w  ww . j  a  va 2 s  .c  o  m

    try {
        HttpResponse httpResponse = httpclient.execute(httpPost);
        if (httpResponse.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
            HttpEntity resEntity = httpResponse.getEntity();
            if (resEntity != null) {
                logger.debug("Response content length: " + resEntity.getContentLength());
                logger.debug("Chunked?: " + resEntity.isChunked());
                BufferedInputStream in = new BufferedInputStream(resEntity.getContent());
                ByteArrayOutputStream resOutputStream = new ByteArrayOutputStream();
                byte[] buff = new byte[32 * 1024];
                int len;
                while ((len = in.read(buff)) > 0) {
                    resOutputStream.write(buff, 0, len);
                }
                response = new String(resOutputStream.toByteArray());
                logger.debug(response);
                resOutputStream.close();
                in.close();
            }
        } else {
            HttpExceptionHandler.deserializeAndThrowException(httpResponse);
        }
    } catch (IOException ex) {
        throw new ServiceFailure("1002", ex.getMessage());
    }
    return response;
}

From source file:com.reactivetechnologies.jaxrs.RestServerTest.java

static String sendGet(String url) throws IOException {

    StringBuilder response = new StringBuilder();
    HttpURLConnection con = null;
    BufferedReader in = null;//from   ww  w.j  a  v  a  2  s. co m
    try {
        URL obj = new URL(url);
        con = (HttpURLConnection) obj.openConnection();

        // optional default is GET
        con.setRequestMethod("GET");

        //add request header
        con.setRequestProperty("User-Agent", "Mozilla/5.0");

        int responseCode = con.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
        } else {
            throw new IOException("Response Code: " + responseCode);
        }

        return response.toString();
    } catch (IOException e) {
        throw e;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {

            }
        }
        if (con != null) {
            con.disconnect();
        }
    }

}

From source file:com.android.internal.util.weather.HttpRetriever.java

private void requestConnectServer(String strURL) throws IOException {
    httpConnection = (HttpURLConnection) new URL(strURL).openConnection();
    httpConnection.connect();//ww  w.jav  a2  s  .  c o  m

    if (httpConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
        Log.e(TAG, "Something wrong with connection");
        httpConnection.disconnect();
        throw new IOException("Error in connection: " + httpConnection.getResponseCode());
    }
}

From source file:com.photon.phresco.nativeapp.eshop.net.NetworkManager.java

public static boolean checkHttpURLStatus(final String url) {
    boolean httpStatusFlag = false;

    HttpClient httpclient = new DefaultHttpClient();
    // Prepare a request object
    HttpGet httpget = new HttpGet(url);
    // Execute the request
    HttpResponse response;/*from   w  w  w  .j  av  a2s.  c o  m*/
    try {
        response = httpclient.execute(httpget);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpURLConnection.HTTP_OK) {
            httpStatusFlag = true;
        }
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return httpStatusFlag;

}

From source file:org.pixmob.fm2.util.HttpUtils.java

/**
 * Download a file./* ww  w  .  ja v a  2  s  .c om*/
 */
public static void downloadToFile(Context context, String uri, Set<String> cookies, File outputFile)
        throws IOException {
    final HttpURLConnection conn = newRequest(context, uri, cookies);
    try {
        conn.connect();

        final int sc = conn.getResponseCode();
        if (sc != HttpURLConnection.HTTP_OK) {
            throw new IOException("Cannot download file: " + uri + "; statusCode=" + sc);
        }

        final InputStream input = getInputStream(conn);
        IOUtils.writeToFile(input, outputFile);
    } finally {
        conn.disconnect();
    }
}

From source file:info.jtrac.mylyn.JtracClient.java

private String doGet(String url) throws Exception {
    HttpMethod get = new GetMethod(url);
    String response = null;//from w ww  . j a  v a 2  s.  com
    int code;
    try {
        code = httpClient.executeMethod(get);
        if (code != HttpURLConnection.HTTP_OK) {
            throw new HttpException("HTTP Response Code: " + code);
        }
        response = get.getResponseBodyAsString();
    } finally {
        get.releaseConnection();
    }
    return response;
}

From source file:eu.peppol.smp.SmpContentRetrieverImpl.java

/**
 * Gets the XML content of a given url, wrapped in an InputSource object.
 *//* ww w  .ja  va2s.c  om*/
@Override
public InputSource getUrlContent(URL url) {

    HttpURLConnection httpURLConnection = null;
    try {
        httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.connect();
    } catch (IOException e) {
        throw new IllegalStateException("Unable to connect to " + url + " ; " + e.getMessage(), e);
    }

    try {
        if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_UNAVAILABLE)
            throw new TryAgainLaterException(url, httpURLConnection.getHeaderField("Retry-After"));
        if (httpURLConnection.getResponseCode() != HttpURLConnection.HTTP_OK)
            throw new ConnectionException(url, httpURLConnection.getResponseCode());
    } catch (IOException e) {
        throw new RuntimeException("Problem reading URL data at " + url.toExternalForm(), e);
    }

    try {

        String encoding = httpURLConnection.getContentEncoding();
        InputStream in = new BOMInputStream(httpURLConnection.getInputStream());
        InputStream result;

        if (encoding != null && encoding.equalsIgnoreCase(ENCODING_GZIP)) {
            result = new GZIPInputStream(in);
        } else if (encoding != null && encoding.equalsIgnoreCase(ENCODING_DEFLATE)) {
            result = new InflaterInputStream(in);
        } else {
            result = in;
        }

        String xml = readInputStreamIntoString(result);

        return new InputSource(new StringReader(xml));

    } catch (Exception e) {
        throw new RuntimeException("Problem reading URL data at " + url.toExternalForm(), e);
    }

}

From source file:mobi.jenkinsci.ci.client.sso.GoogleSsoHandler.java

@Override
public IOException getException(final HttpResponse response) {
    final StatusLine httpStatusLine = response.getStatusLine();
    final int statusCode = httpStatusLine.getStatusCode();
    switch (statusCode) {
    case HttpURLConnection.HTTP_OK:
        try {//from ww  w . ja  v a 2s.  c  o m
            final Document responseDoc = Jsoup.parse(response.getEntity().getContent(), "UTF-8", "");
            final Element errorDiv = responseDoc.select("div[id~=(error|errormsg)").first();
            if (errorDiv != null) {
                return new IOException(getDivText(errorDiv));
            }
        } catch (final Exception e) {
        }
        // Break is not needed here: we want to fallback to the 'default' case
        // if no error div is found

    default:
        return new IOException("Google Authentication FAILED");
    }
}

From source file:com.example.android.sunshine.utilities.OpenWeatherJsonUtils.java

/**
 * This method parses JSON from a web response and returns an array of Strings
 * describing the weather over various days from the forecast.
 * <p/>/*  w w w.  j a v  a2s.c om*/
 * Later on, we'll be parsing the JSON into structured data within the
 * getFullWeatherDataFromJson function, leveraging the data we have stored in the JSON. For
 * now, we just convert the JSON into human-readable strings.
 *
 * @param forecastJsonStr JSON response from server
 *
 * @return Array of Strings describing weather data
 *
 * @throws JSONException If JSON data cannot be properly parsed
 */
public static String[] getSimpleWeatherStringsFromJson(Context context, String forecastJsonStr)
        throws JSONException {

    String[] parsedWeatherData;

    JSONObject forecastJson = new JSONObject(forecastJsonStr);

    /* Is there an error? */
    if (forecastJson.has(OWM_MESSAGE_CODE)) {
        int errorCode = forecastJson.getInt(OWM_MESSAGE_CODE);

        switch (errorCode) {
        case HttpURLConnection.HTTP_OK:
            break;
        case HttpURLConnection.HTTP_NOT_FOUND:
            /* Location invalid */
            return null;
        default:
            /* Server probably down */
            return null;
        }
    }

    JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);

    parsedWeatherData = new String[weatherArray.length()];

    long startDay = SunshineDateUtils.getNormalizedUtcDateForToday();

    for (int i = 0; i < weatherArray.length(); i++) {
        String date;
        String highAndLow;

        /* These are the values that will be collected */
        long dateTimeMillis;
        double high;
        double low;

        int weatherId;
        String description;

        /* Get the JSON object representing the day */
        JSONObject dayForecast = weatherArray.getJSONObject(i);

        /*
         * We ignore all the datetime values embedded in the JSON and assume that
         * the values are returned in-order by day (which is not guaranteed to be correct).
         */
        dateTimeMillis = startDay + SunshineDateUtils.DAY_IN_MILLIS * i;
        date = SunshineDateUtils.getFriendlyDateString(context, dateTimeMillis, false);

        /*
         * Description is in a child array called "weather", which is 1 element long.
         * That element also contains a weather code.
         */
        JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);

        weatherId = weatherObject.getInt(OWM_WEATHER_ID);
        description = SunshineWeatherUtils.getStringForWeatherCondition(context, weatherId);

        /*
         * Temperatures are sent by Open Weather Map in a child object called "temp".
         *
         * Editor's Note: Try not to name variables "temp" when working with temperature.
         * It confuses everybody. Temp could easily mean any number of things, including
         * temperature, temporary and is just a bad variable name.
         */
        JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
        high = temperatureObject.getDouble(OWM_MAX);
        low = temperatureObject.getDouble(OWM_MIN);
        highAndLow = SunshineWeatherUtils.formatHighLows(context, high, low);

        parsedWeatherData[i] = date + " - " + description + " - " + highAndLow;
    }

    return parsedWeatherData;
}