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:net.nym.library.cookie.CookieTest.java

private String getRequest(Context context, String urlString, Map<String, Object> params) throws IOException {
    StringBuffer param = new StringBuffer();
    int i = 0;/*from   ww  w  . jav a  2s. c  om*/
    for (String key : params.keySet()) {
        if (i == 0)
            param.append("?");
        else
            param.append("&");
        param.append(key).append("=").append(params.get(key));
        i++;
    }

    Log.i(urlString + param.toString());
    //URL?
    HttpGet getMethod = new HttpGet(urlString + param.toString());

    DefaultHttpClient client = new DefaultHttpClient();

    client.setCookieStore(new PersistentCookieStore(context));
    HttpResponse response = client.execute(getMethod);
    if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
        String result = EntityUtils.toString(response.getEntity(), "utf-8");
        return result;
    }
    return null;
}

From source file:org.jboss.narayana.rts.TxnHelper.java

public static int endTxn(Client client, Set<Link> links) throws IOException {
    Response response = null;//from ww  w .j  a  va2s.  c  o  m

    try {
        response = client.target(getLink(links, TxLinkNames.TERMINATOR).getUri()).request()
                .put(Entity.entity(TxStatusMediaType.TX_COMMITTED, TxMediaType.TX_STATUS_MEDIA_TYPE));

        int sc = response.getStatus();

        EntityUtils.consume((HttpEntity) response.getEntity());

        if (sc != HttpURLConnection.HTTP_OK)
            throw new RuntimeException("endTxn returned " + sc);

        return sc;
    } finally {
        if (response != null)
            response.close();
    }
}

From source file:foam.blob.RestBlobService.java

@Override
public Blob put_(X x, Blob blob) {
    if (blob instanceof IdentifiedBlob) {
        return blob;
    }//from   w w w.  ja v  a2 s.  com

    HttpURLConnection connection = null;
    OutputStream os = null;
    InputStream is = null;

    try {
        URL url = new URL(address_);
        connection = (HttpURLConnection) url.openConnection();

        //configure HttpURLConnection
        connection.setConnectTimeout(5 * 1000);
        connection.setReadTimeout(5 * 1000);
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        //set request method
        connection.setRequestMethod("PUT");

        //configure http header
        connection.setRequestProperty("Accept", "*/*");
        connection.setRequestProperty("Connection", "keep-alive");
        connection.setRequestProperty("Content-Type", "application/octet-stream");

        // get connection ouput stream
        os = connection.getOutputStream();

        //output blob into connection
        blob.read(os, 0, blob.getSize());

        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new RuntimeException("Upload failed");
        }

        is = connection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        CharBuffer cb = CharBuffer.allocate(65535);
        reader.read(cb);
        cb.rewind();

        return (Blob) getX().create(JSONParser.class).parseString(cb.toString(), IdentifiedBlob.class);
    } catch (Throwable t) {
        t.printStackTrace();
        throw new RuntimeException(t);
    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
        IOUtils.close(connection);
    }
}

From source file:com.sonyericsson.hudson.plugins.gerrit.trigger.utils.GerritPluginChecker.java

/**
 * Given a status code, decode its status.
 * @param statusCode HTTP code//from  w ww  . j a v a2 s .  co  m
 * @param pluginName plugin that was checked.
 * @return true/false if installed or not.
 */
private static boolean decodeStatus(int statusCode, String pluginName) {
    switch (statusCode) {
    case HttpURLConnection.HTTP_OK:
        logger.info(Messages.PluginInstalled(pluginName));
        return true;
    case HttpURLConnection.HTTP_NOT_FOUND:
        logger.info(Messages.PluginNotInstalled(pluginName));
        return false;
    case HttpURLConnection.HTTP_UNAUTHORIZED:
        logger.warn(
                Messages.PluginHttpConnectionUnauthorized(pluginName, Messages.HttpConnectionUnauthorized()));
        return false;
    case HttpURLConnection.HTTP_FORBIDDEN:
        logger.warn(Messages.PluginHttpConnectionForbidden(pluginName, Messages.HttpConnectionUnauthorized()));
        return false;
    default:
        logger.warn(Messages.PluginHttpConnectionGeneralError(pluginName,
                Messages.HttpConnectionError(statusCode)));
        return false;
    }
}

From source file:nl.nn.adapterframework.http.RestSender.java

protected String extractResult(HttpResponseHandler responseHandler, ParameterResolutionContext prc)
        throws SenderException, IOException {
    String responseString = super.extractResult(responseHandler, prc);
    int statusCode = responseHandler.getStatusLine().getStatusCode();
    XmlBuilder result = new XmlBuilder("result");

    XmlBuilder statuscode = new XmlBuilder("statuscode");
    statuscode.setValue(statusCode + "");
    result.addSubElement(statuscode);/*w w  w  .  j av a2 s. c  om*/

    XmlBuilder headersXml = new XmlBuilder("headers");
    Header[] headers = responseHandler.getAllHeaders();
    for (int i = 0; i < headers.length; i++) {
        Header header = headers[i];
        String name = header.getName().toLowerCase();
        XmlBuilder headerXml = new XmlBuilder("header");
        headerXml.addAttribute("name", name);
        headerXml.addAttribute("value", header.getValue());
        headersXml.addSubElement(headerXml);
    }
    result.addSubElement(headersXml);

    if (statusCode == HttpURLConnection.HTTP_OK) {
        XmlBuilder message = new XmlBuilder("message");
        message.setValue(responseString, false);
        result.addSubElement(message);
    } else {
        XmlBuilder message = new XmlBuilder("error");
        message.setValue(responseString);
        result.addSubElement(message);
    }

    return result.toXML();
}

From source file:com.mobile.godot.core.controller.CoreController.java

public synchronized void pop(String username) {

    String servlet = "PopMessage";
    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
    params.add(new BasicNameValuePair("username", username));
    SparseIntArray mMessageMap = new SparseIntArray();
    mMessageMap.append(HttpURLConnection.HTTP_OK, GodotMessage.Core.MESSAGE_READ);

    GodotAction action = new GodotAction(servlet, params, mMessageMap, mHandler);
    Thread tAction = new Thread(action);
    tAction.start();/*w w w  .ja va 2 s .  c om*/

}

From source file:org.dimitrovchi.conf.service.demo.DemoService.java

public DemoService(P parameters) throws IOException {
    super(parameters);
    this.httpServer = HttpServer.create(new InetSocketAddress(parameters.host(), parameters.port()), 0);
    this.httpServer.setExecutor(executor);
    this.httpServer.createContext("/", new HttpHandler() {
        @Override/*from  w w  w  . j a v a2 s. com*/
        public void handle(HttpExchange he) throws IOException {
            he.getResponseHeaders().add("Content-Type", "text/plain; charset=utf-8");
            final byte[] message = "hello!".getBytes(StandardCharsets.UTF_8);
            he.sendResponseHeaders(HttpURLConnection.HTTP_OK, message.length);
            he.getResponseBody().write(message);
        }
    });
    log.info(ServiceParameterUtils.reflectToString("demoService", parameters));
}

From source file:org.openremote.android.console.net.ORNetworkCheck.java

/**
 * Verifies the network access to the currently configured controller URL by checking if
 * REST API {controllerServerURL}/rest/panel/{panel identity} is available.
 *
 * @param context               global Android application context
 * @param url                   an URL to a controller instance
 *
 * @return TODO: returns null or HttpResponse
 *
 * @throws IOException TODO/*  ww  w  . j  av  a  2  s. c  o  m*/
 */
public static HttpResponse verifyControllerURL(Context context, String url) throws IOException {
    // TODO : Use URL class instead of string in param

    // TODO : modifying the settings probably doesn't belong here, as it is an undocumented side-effect
    AppSettingsModel.setCurrentServer(context, url);

    HttpResponse response = isControllerAvailable(context);

    Log.d(LOG_CATEGORY, "HTTP Response: " + response);

    if (response == null)
        return null; // TODO : fix this, it is stupid - throw an exception

    int status = response.getStatusLine().getStatusCode();

    if (status != HttpURLConnection.HTTP_OK)
        return response;

    String controllerURL = AppSettingsModel.getSecuredServer(context);

    if (controllerURL == null || "".equals(controllerURL)) {
        return null; // TODO : fix this, it is stupid - throw an exception
    }

    String currentPanelIdentity = AppSettingsModel.getCurrentPanelIdentity(context);

    if (currentPanelIdentity == null || "".equals(currentPanelIdentity)) {
        return null; // TODO : fix this, it is stupid - throw an exception
    }

    String restfulPanelURL = controllerURL + "/rest/panel/" + HTTPUtil.encodePercentUri(currentPanelIdentity);

    Log.i(LOG_CATEGORY, "Getting panel URL " + restfulPanelURL);

    return ORConnection.checkURLWithHTTPProtocol(context, ORHttpMethod.GET, restfulPanelURL, true);
}

From source file:com.vibeosys.utils.dbdownloadv1.DbDownload.java

public String downloadDatabase() {
    boolean flag = false;
    HttpURLConnection urlConnection = null;
    OutputStream myOutput = null;
    byte[] buffer = null;
    InputStream inputStream = null;
    String message = FAIL;//from www.ja va2  s  . com
    System.out.print(downloadDBURL);
    try {
        URL url = new URL(downloadDBURL);
        urlConnection = (HttpURLConnection) url.openConnection();
        System.out.println("##Request Sent...");

        urlConnection.setDoOutput(true);
        urlConnection.setUseCaches(false);
        urlConnection.setConnectTimeout(20000);
        urlConnection.setReadTimeout(10000);
        urlConnection.connect();

        int Http_Result = urlConnection.getResponseCode();
        String res = urlConnection.getResponseMessage();
        System.out.println(res);
        System.out.println(String.valueOf(Http_Result));
        if (Http_Result == HttpURLConnection.HTTP_OK) {
            String contentType = urlConnection.getContentType();
            inputStream = urlConnection.getInputStream();
            System.out.println(contentType);
            if (contentType.equals("application/octet-stream")) {
                buffer = new byte[1024];
                myOutput = new FileOutputStream(this.dbFile);
                int length;
                while ((length = inputStream.read(buffer)) > 0) {
                    myOutput.write(buffer, 0, length);
                }
                myOutput.flush();
                myOutput.close();
                inputStream.close();
                flag = true;
                message = SUCCESS;
            } else if (contentType.equals("application/json; charset=UTF-8")) {
                message = FAIL;
                flag = false;
                String responce = convertStreamToString(inputStream);
                System.out.println(responce);

                try {
                    JSONObject jsResponce = new JSONObject(responce);
                    message = jsResponce.getString("message");
                } catch (JSONException e) {
                    // addError(screenName, "Json error in downloadDatabase", e.getMessage());
                    System.out.println(e.toString());
                }
            }
        }

    } catch (Exception ex) {
        System.out.println("##ROrder while downloading database" + ex.toString());
        //addError(screenName, "downloadDatabase", ex.getMessage());
    }
    return message;
}

From source file:com.mobile.godot.core.controller.LoginController.java

public synchronized void login(LoginBean login) {

    String servlet = "Login";
    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
    params.add(new BasicNameValuePair("username", login.getUsername()));
    params.add(new BasicNameValuePair("password", login.getPassword()));
    SparseIntArray mMessageMap = new SparseIntArray();
    mMessageMap.append(HttpURLConnection.HTTP_OK, GodotMessage.Session.LOGGED_IN);
    mMessageMap.append(HttpURLConnection.HTTP_UNAUTHORIZED, GodotMessage.Session.NOT_LOGGED);

    GodotAction action = new GodotAction(servlet, params, mMessageMap, mHandler);
    Thread tAction = new Thread(action);
    tAction.start();//from   w  ww .j  ava  2  s. com

}