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.couchbase.client.protocol.views.DesignDocFetcherOperationImpl.java

@Override
public void handleResponse(HttpResponse response) {
    String json = getEntityString(response);
    try {//w w w.  ja  v  a2s.c  om
        int errorcode = response.getStatusLine().getStatusCode();
        if (errorcode == HttpURLConnection.HTTP_OK) {
            DesignDocument design = parseDesignDocument(designDocName, json);
            ((DesignDocFetcherCallback) callback).gotData(design);
            callback.receivedStatus(new OperationStatus(true, "OK"));
        } else {
            callback.receivedStatus(new OperationStatus(false, Integer.toString(errorcode)));
        }
    } catch (ParseException e) {
        exception = new OperationException(OperationErrorType.GENERAL, "Error parsing JSON");
    }
    callback.complete();
}

From source file:org.gameontext.regsvc.RegistrationEndpoint.java

/**
  * POST /regsvc/v1/register/*from ww w  .  j  a  v a  2 s  . c o m*/
  * @throws JsonProcessingException
  */
@POST
@ApiOperation(value = "Create a new registration", notes = "Register a room for a given event", code = HttpURLConnection.HTTP_OK)
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response registerRoom(@ApiParam(value = "Room to register", required = true) Registration registration) {
    registration.setId(registration.getSiteId()); //use the site id as the doc id for the database
    if (repo.createRegistration(registration)) {
        return Response.ok(registration).build();
    } else {
        //this ID already exists
        return Response.status(Status.CONFLICT).build();
    }
}

From source file:de.intevation.irix.ImageClient.java

/** Obtains a Report from mapfish-print service.
 *
 * @param imageUrl The url to send the request to.
 * @param timeout the timeout for the httpconnection.
 *
 * @return byte[] with the report.// w  w  w  .  j  a v a2 s. c  om
 *
 * @throws IOException if communication with print service failed.
 * @throws ImageException if the print job failed.
 */
public static byte[] getImage(String imageUrl, int timeout) throws IOException, ImageException {

    RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout).build();

    CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(config).build();

    HttpGet get = new HttpGet(imageUrl);
    CloseableHttpResponse resp = client.execute(get);

    StatusLine status = resp.getStatusLine();

    byte[] retval = null;
    try {
        HttpEntity respEnt = resp.getEntity();
        InputStream in = respEnt.getContent();
        if (in != null) {
            try {
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                byte[] buf = new byte[BYTE_ARRAY_SIZE];
                int r;
                while ((r = in.read(buf)) >= 0) {
                    out.write(buf, 0, r);
                }
                retval = out.toByteArray();
            } finally {
                in.close();
                EntityUtils.consume(respEnt);
            }
        }
    } finally {
        resp.close();
    }

    if (status.getStatusCode() < HttpURLConnection.HTTP_OK
            || status.getStatusCode() >= HttpURLConnection.HTTP_MULT_CHOICE) {
        if (retval != null) {
            throw new ImageException(new String(retval));
        } else {
            throw new ImageException("Communication with print service '" + imageUrl + "' failed."
                    + "\nNo response from print service.");
        }
    }
    return retval;
}

From source file:org.cytoscape.app.internal.net.server.AddAllowOriginHeaderTest.java

@Test
public void testAddAccessControlAllowOriginHeader() throws Exception {
    final CyHttpd httpd = (new CyHttpdFactoryImpl()).createHttpd(new LocalhostServerSocketFactory(2611));
    final CyHttpResponseFactory responseFactory = new CyHttpResponseFactoryImpl();
    httpd.addResponder(new CyHttpResponder() {
        public Pattern getURIPattern() {
            return Pattern.compile("^/test$");
        }/*from  w  w  w .  j  a  v  a2 s.  co  m*/

        public CyHttpResponse respond(CyHttpRequest request, Matcher matchedURI) {
            return responseFactory.createHttpResponse(HttpStatus.SC_OK, "test response ok", "text/html");
        }
    });
    httpd.addAfterResponse(new AddAllowOriginHeader());
    httpd.start();

    HttpURLConnection connection = null;
    final String url = "http://localhost:2611/test";

    connection = connectToURL(url, "GET");
    assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_OK);
    assertEquals(connection.getHeaderField("Access-Control-Allow-Origin"), "*");
    assertEquals(readConnection(connection), "test response ok");

    httpd.stop();
}

From source file:org.cytoscape.app.internal.net.server.OriginOptionsBeforeResponseTest.java

@Test
public void testOptions() throws Exception {
    final CyHttpd httpd = (new CyHttpdFactoryImpl()).createHttpd(new LocalhostServerSocketFactory(2610));
    final CyHttpResponseFactory responseFactory = new CyHttpResponseFactoryImpl();
    httpd.addResponder(new CyHttpResponder() {
        public Pattern getURIPattern() {
            return Pattern.compile("^/test$");
        }//from w  w w.  j  a v a  2s .  co  m

        public CyHttpResponse respond(CyHttpRequest request, Matcher matchedURI) {
            return responseFactory.createHttpResponse(HttpStatus.SC_OK, "test response ok", "text/html");
        }
    });
    httpd.addBeforeResponse(new OriginOptionsBeforeResponse());
    httpd.start();

    HttpURLConnection connection = null;
    final String url = "http://localhost:2610/test";

    connection = connectToURL(url, "OPTIONS");
    assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_OK);
    assertEquals(connection.getHeaderField("Access-Control-Allow-Origin"), "*");
    assertEquals(connection.getHeaderField("Access-Control-Allow-Methods"), "POST, PUT, GET, OPTIONS");
    assertEquals(connection.getHeaderField("Access-Control-Max-Age"), "1");
    assertEquals(connection.getHeaderField("Access-Control-Allow-Headers"), "origin, accept");

    connection = connectToURL(url, "GET");
    assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_OK);
    assertEquals(readConnection(connection), "test response ok");

    httpd.stop();
}

From source file:net.spy.memcached.protocol.couch.ViewsFetcherOperationImpl.java

@Override
public void handleResponse(HttpResponse response) {
    String json = getEntityString(response);
    try {//from   w w  w  .j  av  a  2 s  .  co  m
        int errorcode = response.getStatusLine().getStatusCode();
        if (errorcode == HttpURLConnection.HTTP_OK) {
            List<View> views = parseDesignDocumentForViews(bucketName, designDocName, json);
            ((ViewsFetcherCallback) callback).gotData(views);
            callback.receivedStatus(new OperationStatus(true, "OK"));
        } else {
            callback.receivedStatus(new OperationStatus(false, Integer.toString(errorcode)));
        }
    } catch (ParseException e) {
        exception = new OperationException(OperationErrorType.GENERAL, "Error parsing JSON");
    }
    callback.complete();
}

From source file:org.cytoscape.app.internal.net.server.AddAccessControlAllowOriginHeaderAfterResponseTest.java

@Test
public void testAddAccessControlAllowOriginHeader() throws Exception {
    final CyHttpd httpd = (new CyHttpdFactoryImpl()).createHttpd(new LocalhostServerSocketFactory(2611));
    final CyHttpResponseFactory responseFactory = new CyHttpResponseFactoryImpl();
    httpd.addResponder(new CyHttpResponder() {
        public Pattern getURIPattern() {
            return Pattern.compile("^/test$");
        }/*from   w  w  w.  j  a  v a 2s .  com*/

        public CyHttpResponse respond(CyHttpRequest request, Matcher matchedURI) {
            return responseFactory.createHttpResponse(HttpStatus.SC_OK, "test response ok", "text/html");
        }
    });
    httpd.addAfterResponse(new AddAccessControlAllowOriginHeaderAfterResponse());
    httpd.start();

    HttpURLConnection connection = null;
    final String url = "http://localhost:2611/test";

    connection = connectToURL(url, "GET");
    assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_OK);
    assertEquals(connection.getHeaderField("Access-Control-Allow-Origin"), "*");
    assertEquals(readConnection(connection), "test response ok");

    httpd.stop();
}

From source file:com.adaptris.http.legacy.GenericConsumer.java

/**
 * @see HttpConsumerImp#handleRequest(HttpSession)
 *///from  ww w  .  j  a  va2  s. co m
@Override
@SuppressWarnings("deprecation")
protected AdaptrisMessage handleRequest(HttpSession httpSession)
        throws IOException, IllegalStateException, HttpException {

    HttpRequest request = httpSession.getRequestLine();
    HttpMessage message = httpSession.getRequestMessage();
    HttpHeaders header = message.getHeaders();

    HttpResponse response = httpSession.getResponseLine();

    AdaptrisMessage result = null;
    OutputStream out = null;
    try {
        // By default we only accept post methods
        if (request.getMethod().equalsIgnoreCase(getMethod())) {
            response.setResponseCode(HttpURLConnection.HTTP_OK);
            response.setResponseMessage("OK");
            if (getEncoder() != null) {
                result = getEncoder().readMessage(message);
            } else {
                result = defaultIfNull(getMessageFactory()).newMessage();
                out = result.getOutputStream();
                StreamUtil.copyStream(message.getInputStream(), out, header.getContentLength());
            }
            result.addObjectHeader(CoreConstants.HTTP_SESSION_KEY, httpSession);
            addParamsAsMetadata(httpSession, result);
        } else {
            response.setResponseCode(HttpURLConnection.HTTP_BAD_METHOD);
            response.setResponseMessage("Method Not Allowed");
        }
    } catch (CoreException e) {
        throw new HttpException(e);
    } finally {
        IOUtils.closeQuietly(out);
    }

    return result;
}

From source file:com.couchbase.client.protocol.views.ViewsFetcherOperationImpl.java

@Override
public void handleResponse(HttpResponse response) {
    String json = getEntityString(response);
    try {//from  w w  w. ja  va  2  s  .c  o m
        int errorcode = response.getStatusLine().getStatusCode();
        if (errorcode == HttpURLConnection.HTTP_OK) {
            List<View> views = parseDesignDocumentForViews(bucketName, designDocName, json);
            ((ViewsFetcherCallback) callback).gotData(views);
            callback.receivedStatus(new OperationStatus(true, "OK", ErrorCode.SUCCESS));
        } else {
            callback.receivedStatus(
                    new OperationStatus(false, Integer.toString(errorcode), ErrorCode.ERR_INVAL));
        }
    } catch (ParseException e) {
        exception = new OperationException(OperationErrorType.GENERAL, "Error parsing JSON");
    }
    callback.complete();
}

From source file:com.pubkit.network.PubKitNetwork.java

public static JSONObject sendPost(String apiKey, JSONObject jsonObject) {
    URL url;/*www.  j ava  2 s .  co m*/
    HttpURLConnection connection = null;
    try {
        //Create connection
        url = new URL(PUBKIT_API_URL);
        String encodedData = jsonObject.toString();
        byte[] postDataBytes = jsonObject.toString().getBytes("UTF-8");

        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Content-Length", "" + String.valueOf(postDataBytes.length));
        connection.setRequestProperty("api_key", apiKey);

        connection.setUseCaches(false);
        connection.setDoOutput(true);

        //Send request
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(encodedData);//set data
        wr.flush();

        //Get Response
        InputStream inputStream = connection.getErrorStream(); //first check for error.
        if (inputStream == null) {
            inputStream = connection.getInputStream();
        }
        BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));

        String line;
        StringBuilder response = new StringBuilder();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        wr.close();
        rd.close();

        String responseString = response.toString();
        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            return new JSONObject("{'error':'" + responseString + "'}");
        } else {
            try {
                return new JSONObject(responseString);
            } catch (JSONException e) {
                Log.e("PUBKIT", "Error parsing data", e);
            }
        }
    } catch (Exception e) {
        Log.e("PUBKIT", "Network exception:", e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
    return null;
}