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:com.openforevent.main.UserPosition.java

public static Map<String, Object> userPositionByIP(DispatchContext ctx, Map<String, ? extends Object> context)
        throws IOException {
    URL url = new URL("http://api.ipinfodb.com/v3/ip-city/?" + "key=" + ipinfodb_key + "&" + "&ip=" + default_ip
            + "&format=xml");
    //URL url = new URL("http://ipinfodb.com/ip_query.php");
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

    // Set properties of the connection
    urlConnection.setRequestMethod("GET");
    urlConnection.setDoInput(true);//from   w w w.  jav  a 2s  .c o  m
    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("Get user position by IP stream is = ", theString);

    Map<String, Object> paramOut = FastMap.newInstance();
    paramOut.put("stream", theString);
    return paramOut;
}

From source file:com.datos.vfs.provider.url.UrlFileObject.java

/**
 * Determines the type of the file./*from   w  w  w. j av  a 2 s . c o  m*/
 */
@Override
protected FileType doGetType() throws Exception {
    try {
        // Attempt to connect & check status
        final URLConnection conn = url.openConnection();
        final InputStream in = conn.getInputStream();
        try {
            if (conn instanceof HttpURLConnection) {
                final int status = ((HttpURLConnection) conn).getResponseCode();
                // 200 is good, maybe add more later...
                if (HttpURLConnection.HTTP_OK != status) {
                    return FileType.IMAGINARY;
                }
            }

            return FileType.FILE;
        } finally {
            in.close();
        }
    } catch (final FileNotFoundException e) {
        return FileType.IMAGINARY;
    }
}

From source file:freemarker.test.servlet.WebAppTestCase.java

protected final String getResponseContent(String webAppName, String webAppRelURL) throws Exception {
    HTTPResponse resp = getHTTPResponse(webAppName, webAppRelURL);
    if (resp.getStatusCode() != HttpURLConnection.HTTP_OK) {
        fail("Expected HTTP status " + HttpURLConnection.HTTP_OK + ", but got " + resp.getStatusCode()
                + " (message: " + resp.getStatusMessage() + ") for URI " + resp.getURI());
    }/*from w ww  .ja  v a  2 s. c o  m*/
    return resp.getContent();
}

From source file:blueprint.sdk.google.gcm.GcmSender.java

/**
 * decodes response from GCM/*from   w w w. j  ava 2s. c o m*/
 *
 * @param http HTTP connection
 * @return response from GCM
 * @throws IOException
 */
@SuppressWarnings("ResultOfMethodCallIgnored")
private GcmResponse decodeResponse(HttpURLConnection http) throws IOException {
    GcmResponse result = new GcmResponse();
    result.code = getResponseCode(http);

    if (result.code == HttpURLConnection.HTTP_OK) {
        try {
            Response response = mapper.readValue((InputStream) http.getContent(), Response.class);
            result.multicastId = response.multicast_id;
            result.success = response.success;
            result.failure = response.failure;
            result.canonicalIds = response.canonical_ids;

            // decode 'results'
            for (Map<String, String> item : response.results) {
                GcmResponseDetail detail = new GcmResponseDetail();

                if (item.containsKey("message_id")) {
                    detail.success = true;
                    detail.message = item.get("message_id");
                } else {
                    detail.success = false;
                    detail.message = item.get("error");
                }

                result.results.add(detail);
            }
        } catch (Exception e) {
            result.code = GcmResponse.ERR_JSON_BIND;

            L.warn("Can't bind json", e);
        }
    } else if (result.code == GcmResponse.ERR_NOT_JSON) {
        int contentLength = http.getContentLength();
        String contentType = http.getContentType();

        InputStream ins = (InputStream) http.getContent();
        byte[] buffer = new byte[contentLength];
        ins.read(buffer);

        L.warn("response message is not a json. content-type=" + contentType + ", content="
                + new String(buffer));
    }

    return result;
}

From source file:org.ow2.proactive_grid_cloud_portal.scheduler.HttpResourceDownloader.java

private boolean responseIsNotHttpOk(Response response) {
    return response.getStatus() != HttpURLConnection.HTTP_OK;
}

From source file:com.aokyu.dev.pocket.PocketClient.java

public AccessToken authenticate(RequestToken requestToken)
        throws IOException, InvalidRequestException, PocketException {
    String endpoint = PocketServer.getEndpoint(RequestType.OAUTH_AUTHORIZE);
    URL requestUrl = new URL(endpoint);
    HttpHeaders headers = new HttpHeaders();
    headers.put(HttpHeader.CONTENT_TYPE, ContentType.JSON_WITH_UTF8.get());
    headers.put(HttpHeader.X_ACCEPT, ContentType.JSON.get());
    headers.put(HttpHeader.HOST, requestUrl.getHost());

    HttpParameters parameters = new HttpParameters();
    parameters.put(AuthRequestParameter.CONSUMER_KEY, mConsumerKey.get());
    parameters.put(AuthRequestParameter.CODE, requestToken.get());

    HttpRequest request = new HttpRequest(HttpMethod.POST, requestUrl, headers, parameters);

    HttpResponse response = null;//from www  . j a va 2s  . c  o  m
    AccessToken accessToken = null;
    try {
        response = mClient.execute(request);
        if (response.getStatusCode() == HttpURLConnection.HTTP_OK) {
            JSONObject jsonObj = response.getResponseAsJSONObject();
            accessToken = new AccessToken(jsonObj);
        } else {
            ErrorResponse error = new ErrorResponse(response);
            mErrorHandler.handleResponse(error);
        }
    } catch (JSONException e) {
        throw new PocketException(e.getMessage());
    } finally {
        if (response != null) {
            response.disconnect();
        }
    }

    return accessToken;
}

From source file:org.apache.calcite.avatica.remote.AvaticaCommonsHttpClientImplTest.java

@Test
public void testRetryOnHttp503() throws Exception {
    final byte[] requestBytes = "fake_request".getBytes(UTF_8);
    final CloseableHttpResponse badResponse = mock(CloseableHttpResponse.class);
    final CloseableHttpResponse goodResponse = mock(CloseableHttpResponse.class);
    final StatusLine badStatusLine = mock(StatusLine.class);
    final StatusLine goodStatusLine = mock(StatusLine.class);
    final StringEntity responseEntity = new StringEntity("success");
    final Answer<CloseableHttpResponse> failThenSucceed = new Answer<CloseableHttpResponse>() {
        private int iteration = 0;

        @Override//w w  w.java  2s. c o m
        public CloseableHttpResponse answer(InvocationOnMock invocation) throws Throwable {
            iteration++;
            if (1 == iteration) {
                return badResponse;
            } else {
                return goodResponse;
            }
        }
    };

    final AvaticaCommonsHttpClientImpl client = mock(AvaticaCommonsHttpClientImpl.class);

    when(client.send(any(byte[].class))).thenCallRealMethod();
    when(client.execute(any(HttpPost.class), any(HttpClientContext.class))).then(failThenSucceed);

    when(badResponse.getStatusLine()).thenReturn(badStatusLine);
    when(badStatusLine.getStatusCode()).thenReturn(HttpURLConnection.HTTP_UNAVAILABLE);

    when(goodResponse.getStatusLine()).thenReturn(goodStatusLine);
    when(goodStatusLine.getStatusCode()).thenReturn(HttpURLConnection.HTTP_OK);
    when(goodResponse.getEntity()).thenReturn(responseEntity);

    byte[] responseBytes = client.send(requestBytes);
    assertEquals("success", new String(responseBytes, UTF_8));
}

From source file:io.bibleget.HTTPCaller.java

public String getResponse(String url) {
    URL obj;//from   w w  w . j  a  va 2s. com
    try {
        obj = new URL(url);
        HttpURLConnection con;
        con = (HttpURLConnection) obj.openConnection();

        // optional default is GET
        con.setRequestMethod("GET");
        con.setRequestProperty("Accept-Charset", "UTF-8");

        //System.out.println("Sending 'GET' request to URL : " + url);
        //System.out.println("Response Code : " + con.getResponseCode());
        if (HttpURLConnection.HTTP_OK == con.getResponseCode()) {
            StringBuilder response;
            try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"))) {
                String inputLine;
                response = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                con.disconnect();
                return response.toString();
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(HTTPCaller.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:com.stackmob.customcode.util.Logging.java

@Override
public ResponseToProcess execute(ProcessedAPIRequest request, SDKServiceProvider serviceProvider) {
    // Initialize logger to "Classnamehere.class" when calling serviceProvider.getLoggerService()
    LoggerService logger = serviceProvider.getLoggerService(Logging.class);
    Map<String, String> errMap = new HashMap<String, String>();

    String model = "";
    String make = "";
    String year = "";

    JSONParser parser = new JSONParser();

    /* The following try/catch block shows how to properly fetch parameters for PUT/POST operations
     * from the JSON request body. In order to get parameters from GET/DELETE operations,
     * you must use request.getParams() (see DeleteObject.java)
     *//*from   ww w .  ja  v a2s.  c  o m*/
    try {
        Object obj = parser.parse(request.getBody());
        JSONObject jsonObject = (JSONObject) obj;
        model = (String) jsonObject.get("model");
        make = (String) jsonObject.get("make");
        year = (String) jsonObject.get("year");

        logger.debug("Model: " + model);
        logger.debug("Make: " + make);
        logger.debug("Year: " + year.toString());
    } catch (ParseException pe) {
        // error("Message", Throwable)
        logger.error(pe.getMessage(), pe);
        return Util.badRequestResponse(errMap, pe.getMessage());
    }

    Map<String, Object> map = new HashMap<String, Object>();
    map.put("model", new SMString(model));
    map.put("make", new SMString(make));
    map.put("year", new SMInt(Long.parseLong(year)));

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

From source file:org.cm.podd.report.util.RequestDataUtil.java

public static ResponseObject post(String path, String query, String json, String token) {
    JSONObject jsonObj = null;/*from   w w  w .  j  a  v a  2s .  c  o  m*/
    int statusCode = 0;

    //SharedPreferences settings = PoddApplication.getAppContext().getSharedPreferences("PoddPrefsFile", 0);
    String serverUrl = settings.getString("serverUrl", BuildConfig.SERVER_URL);
    String reqUrl = "";

    if (path.contains("http://") || path.contains("https://")) {
        reqUrl = String.format("%s%s", path, query == null ? "" : "?" + query);
    } else {
        reqUrl = String.format("%s%s%s", serverUrl, path, query == null ? "" : "?" + query);
    }

    Log.i(TAG, "submit url=" + reqUrl);
    Log.i(TAG, "post data=" + json);

    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    HttpClient client = new DefaultHttpClient(params);

    try {
        HttpPost post = new HttpPost(reqUrl);
        post.setHeader("Content-Type", "application/json");
        if (token != null) {
            post.setHeader("Authorization", "Token " + token);
        }
        post.setEntity(new StringEntity(json, HTTP.UTF_8));

        HttpResponse response;
        response = client.execute(post);
        HttpEntity entity = response.getEntity();

        // Detect server complaints
        statusCode = response.getStatusLine().getStatusCode();
        Log.v(TAG, "status code=" + statusCode);

        if (statusCode == HttpURLConnection.HTTP_OK || statusCode == HttpURLConnection.HTTP_CREATED
                || statusCode == HttpURLConnection.HTTP_BAD_REQUEST) {
            InputStream in = entity.getContent();
            String resp = FileUtil.convertInputStreamToString(in);

            jsonObj = new JSONObject(resp);
            entity.consumeContent();
        }

    } catch (ClientProtocolException e) {
        Log.e(TAG, "error post data", e);
    } catch (IOException e) {
        Log.e(TAG, "Can't connect server", e);
    } catch (JSONException e) {
        Log.e(TAG, "error convert json", e);
    } finally {
        client.getConnectionManager().shutdown();
    }
    return new ResponseObject(statusCode, jsonObj);
}