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:de.ub0r.android.websms.connector.smstrade.ConnectorSMStrade.java

/**
 * Send data./*  w w  w  .ja v  a  2  s . com*/
 * 
 * @param context
 *            {@link Context}
 * @param command
 *            {@link ConnectorCommand}
 */
private void sendData(final Context context, final ConnectorCommand command) {
    // do IO
    try { // get Connection
        final StringBuilder url = new StringBuilder(URL);
        final ConnectorSpec cs = this.getSpec(context);
        final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context);
        url.append("?user=");
        url.append(Utils.international2oldformat(Utils.getSender(context, command.getDefSender())));
        url.append("&password=");
        url.append(Utils.md5(p.getString(Preferences.PREFS_PASSWORD, "")));
        final String text = command.getText();
        if (text != null && text.length() > 0) {
            final String sub = command.getSelectedSubConnector();
            url.append("&route=");
            url.append(sub);
            url.append("&message=");
            url.append(URLEncoder.encode(text, "ISO-8859-15"));
            url.append("&to=");
            url.append(Utils.joinRecipientsNumbers(
                    Utils.national2international(command.getDefPrefix(), command.getRecipients()), ";", true));
        } else {
            url.append("credits/");
        }
        Log.d(TAG, "--HTTP GET--");
        Log.d(TAG, url.toString());
        Log.d(TAG, "--HTTP GET--");
        // send data
        HttpResponse response = Utils.getHttpClient(url.toString(), null, null, null, null, false);
        int resp = response.getStatusLine().getStatusCode();
        if (resp != HttpURLConnection.HTTP_OK) {
            throw new WebSMSException(context, R.string.error_http, "" + resp);
        }
        String htmlText = Utils.stream2str(response.getEntity().getContent()).trim();
        if (htmlText == null || htmlText.length() == 0) {
            throw new WebSMSException(context, R.string.error_service);
        }
        Log.d(TAG, "--HTTP RESPONSE--");
        Log.d(TAG, htmlText);
        Log.d(TAG, "--HTTP RESPONSE--");
        String[] lines = htmlText.split("\n");
        htmlText = null;
        int l = lines.length;
        if (text != null && text.length() > 0) {
            try {
                final int ret = Integer.parseInt(lines[0].trim());
                checkReturnCode(context, ret);
                if (l > 1) {
                    cs.setBalance(lines[l - 1].trim());
                }
            } catch (NumberFormatException e) {
                Log.e(TAG, "could not parse ret", e);
                throw new WebSMSException(e.getMessage());
            }
        } else {
            cs.setBalance(lines[l - 1].trim());
        }
    } catch (Exception e) {
        Log.e(TAG, null, e);
        throw new WebSMSException(e.getMessage());
    }
}

From source file:i5.las2peer.services.gamificationGamifierService.GamificationGamifierService.java

/**
 * Get action data from database/*from w  w w .  ja  v  a  2s  .  c om*/
 * @param appId applicationId
 * @return HttpResponse Returned as JSON object
 */
@GET
@Path("/actions/{appId}")
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Fetch the actions"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal Error"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
public HttpResponse getActions(@ApiParam(value = "Application ID") @PathParam("appId") String appId) {
    JSONObject objResponse = new JSONObject();
    UserAgent userAgent = (UserAgent) getContext().getMainAgent();
    String name = userAgent.getLoginName();
    if (name.equals("anonymous")) {
        return unauthorizedMessage();
    }
    String memberId = name;
    //      try {      
    //            if(!initializeDBConnection()){
    //            logger.info("Cannot connect to database >> ");
    //            objResponse.put("message", "Cannot connect to database");
    //            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
    //            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    //         }

    // RMI call with parameters
    try {
        Object result = this.invokeServiceMethod(
                "i5.las2peer.services.gamificationActionService.GamificationActionService@0.1", "getActionsRMI",
                new Serializable[] { appId });
        if (result != null) {
            L2pLogger.logEvent(Event.RMI_SUCCESSFUL, "Get Actions RMI success");
            return new HttpResponse((String) result, HttpURLConnection.HTTP_OK);
        }
        L2pLogger.logEvent(Event.RMI_FAILED, "Get Actions RMI failed");
        objResponse.put("message", "Cannot find actions");
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);

    } catch (AgentNotKnownException | L2pServiceException | L2pSecurityException | InterruptedException
            | TimeoutException e) {
        e.printStackTrace();
        L2pLogger.logEvent(Event.RMI_FAILED, "Get Actions RMI failed. " + e.getMessage());
        objResponse.put("message", "Cannot find Actions. " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);

    }

    //      } catch (SQLException e) {
    //         e.printStackTrace();
    //         objResponse.put("message", "DB Error. " + e.getMessage());
    //         L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
    //         return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
    //
    //      }
}

From source file:com.bellman.bible.service.common.CommonUtils.java

/** return true if URL is accessible
 * //from w  ww . j  av  a 2 s.c  om
 * Since Android 3 must do on different or NetworkOnMainThreadException is thrown
 */
public static boolean isHttpUrlAvailable(final String urlString) {
    boolean isAvailable = false;
    final int TIMEOUT_MILLIS = 3000;

    try {
        class CheckUrlThread extends Thread {
            public boolean checkUrlSuccess = false;

            public void run() {
                HttpURLConnection connection = null;
                try {
                    // might as well test for the url we need to access
                    URL url = new URL(urlString);

                    Log.d(TAG, "Opening test connection");
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(TIMEOUT_MILLIS);
                    connection.setReadTimeout(TIMEOUT_MILLIS);
                    connection.setRequestMethod("HEAD");
                    Log.d(TAG, "Connecting to test internet connection");
                    connection.connect();
                    checkUrlSuccess = (connection.getResponseCode() == HttpURLConnection.HTTP_OK);
                    Log.d(TAG, "Url test result for:" + urlString + " is " + checkUrlSuccess);
                } catch (IOException e) {
                    Log.i(TAG, "No internet connection");
                    checkUrlSuccess = false;
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }

        CheckUrlThread checkThread = new CheckUrlThread();
        checkThread.start();
        checkThread.join(TIMEOUT_MILLIS);
        isAvailable = checkThread.checkUrlSuccess;
    } catch (InterruptedException e) {
        Log.e(TAG, "Interrupted waiting for url check to complete", e);
    }
    return isAvailable;
}

From source file:eu.geopaparazzi.library.network.NetworkUtilities.java

/**
 * Sends a string via POST to a given url.
 * //from  w  w w  . j  a  va  2s.c  o m
 * @param urlStr the url to which to send to.
 * @param string the string to send as post body.
 * @param user the user or <code>null</code>.
 * @param password the password or <code>null</code>.
 * @return the response.
 * @throws Exception
 */
public static String sendPost(String urlStr, String string, String user, String password) throws Exception {
    BufferedOutputStream wr = null;
    HttpURLConnection conn = null;
    try {
        conn = makeNewConnection(urlStr);
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        // conn.setChunkedStreamingMode(0);
        conn.setUseCaches(false);
        if (user != null && password != null) {
            conn.setRequestProperty("Authorization", getB64Auth(user, password));
        }
        conn.connect();

        // Make server believe we are form data...
        wr = new BufferedOutputStream(conn.getOutputStream());
        byte[] bytes = string.getBytes();
        wr.write(bytes);
        wr.flush();

        int responseCode = conn.getResponseCode();
        StringBuilder returnMessageBuilder = new StringBuilder();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            while (true) {
                String line = br.readLine();
                if (line == null)
                    break;
                returnMessageBuilder.append(line + "\n");
            }
            br.close();
        }

        return returnMessageBuilder.toString();
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    } finally {
        if (conn != null)
            conn.disconnect();
    }
}

From source file:org.eclipse.hono.client.impl.TenantClientImpl.java

/**
 * {@inheritDoc}//from  w  ww  .  j  a  v  a  2 s .c  o  m
 */
@Override
public final Future<TenantObject> get(final String tenantId) {

    final TriTuple<TenantAction, String, Object> key = TriTuple.of(TenantAction.get, tenantId, null);

    return getResponseFromCache(key).recover(t -> {
        final Future<TenantResult<TenantObject>> tenantResult = Future.future();
        createAndSendRequest(TenantConstants.TenantAction.get.toString(), createTenantProperties(tenantId),
                null, tenantResult.completer(), key);
        return tenantResult;
    }).map(tenantResult -> {
        switch (tenantResult.getStatus()) {
        case HttpURLConnection.HTTP_OK:
            return tenantResult.getPayload();
        default:
            throw StatusCodeMapper.from(tenantResult);
        }
    });
}

From source file:co.cask.cdap.security.authentication.client.AbstractAuthenticationClient.java

/**
 * Executes fetch access token request./*from www .j ava2s  .  c o  m*/
 *
 * @param request the http request to fetch access token from the authentication server
 * @return {@link AccessToken} object containing the access token
 * @throws IOException IOException in case of a problem or the connection was aborted or if the access token is not
 * received successfully from the authentication server
 */
private AccessToken execute(HttpRequest request) throws IOException {
    HttpResponse response = HttpRequests.execute(request, getHttpRequestConfig());

    LOG.debug("Got response {} - {} from {}", response.getResponseCode(), response.getResponseMessage(),
            baseURI);
    if (response.getResponseCode() != HttpURLConnection.HTTP_OK) {
        throw new HttpFailureException(response.getResponseMessage(), response.getResponseCode());
    }

    Map<String, String> responseMap = ObjectResponse
            .fromJsonBody(response, new TypeToken<Map<String, String>>() {
            }).getResponseObject();
    String tokenValue = responseMap.get(ACCESS_TOKEN_KEY);
    String tokenType = responseMap.get(TOKEN_TYPE_KEY);
    String expiresInStr = responseMap.get(EXPIRES_IN_KEY);

    LOG.debug("Response map from auth server: {}", responseMap);

    if (StringUtils.isEmpty(tokenValue) || StringUtils.isEmpty(tokenType)
            || StringUtils.isEmpty(expiresInStr)) {
        throw new IOException("Unexpected response was received from the authentication server.");
    }

    return new AccessToken(tokenValue, Long.valueOf(expiresInStr), tokenType);
}

From source file:brainleg.app.util.AppWeb.java

public static String post(String url, NameValuePair[] postParameters)
        throws RequestRejectedException, IOException {
    HttpConfigurable.getInstance().prepareURL(getUrl("api/proxyTest"));

    HttpURLConnection connection = doPost(url, join(Arrays.asList(postParameters)));
    int responseCode = connection.getResponseCode();

    String responseText;//from   w w  w. j a  v  a  2 s . com

    InputStream is = new BufferedInputStream(connection.getInputStream());
    try {
        responseText = readFrom(is);
    } finally {
        is.close();
    }

    if (responseCode != HttpURLConnection.HTTP_OK) {
        // if this is 400 this is an application error (something is rejected by the app)
        if (responseCode == 400 && responseText != null) {
            //normally we return error messages like this: REQUIRED_PARAM_MISSING:Required parameters missing
            List<String> tokens = Lists
                    .newArrayList(Splitter.on(":").omitEmptyStrings().trimResults().split(responseText));
            if (tokens.isEmpty()) {
                throw new RequestRejectedException();
            } else if (tokens.size() == 1) {
                throw new RequestRejectedException(tokens.get(0), null);
            } else {
                throw new RequestRejectedException(tokens.get(0), tokens.get(1));
            }
        } else {
            throw new IOException("response code from server: " + responseCode);
        }
    } else {
        return responseText;
    }
}

From source file:mobi.jenkinsci.alm.assembla.client.AssemblaClient.java

public void login() throws IOException {
    Document pinDoc = Jsoup.parse(getData(String.format(AUTH, appId), false));
    if (getLatestRedirectedUrl().getPath().startsWith(LOGIN)) {
        pinDoc = postLoginForm(pinDoc);//from   w w  w .  ja  v  a  2  s  .  c o m
    }

    final Element pinBox = pinDoc.select("div[class=box]").first();
    if (pinBox == null) {
        throw new IOException("Missing PIN code from Assembla auth response");
    }
    final Element pinLabel = pinBox.select("p").first();
    final Element pinValue = pinBox.select("h1").first();
    if (pinLabel == null || pinValue == null) {
        throw new IOException("Missing PIN code from Assembla auth response");
    }
    final String pin = pinValue.childNode(0).toString();
    final HttpPost authPost = new HttpPost(
            String.format(ASSEMBLA_SITE_APP_AUTH, appId, appSecret) + String.format(PIN_AUTH, pin));
    final HttpResponse pinResponse = httpClient.execute(authPost);
    try {
        if (pinResponse.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_OK) {
            throw new IOException(
                    "Post " + authPost.getURI() + " for a PIN failed: " + pinResponse.getStatusLine());
        }
        accessToken = gson.fromJson(
                new JsonReader(new InputStreamReader(pinResponse.getEntity().getContent(), "UTF-8")),
                AssemblaAccessToken.class);
    } finally {
        authPost.releaseConnection();
    }
}

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

/**
 * Upload ontology content on specified dataset. Graph used is the default
 * one except if specified/*from w  w  w .  j a  v a 2s . c om*/
 * 
 * @param ontology
 * @param datasetName
 * @param graphName
 * @throws IOException
 * @throws HttpException
 */
public static void uploadOntology(InputStream ontology, String datasetName, @Nullable String graphName)
        throws IOException, HttpException {
    graphName = Strings.emptyToNull(graphName);

    logger.info("upload ontology in dataset: " + datasetName + " graph:" + Strings.nullToEmpty(graphName));

    boolean createGraph = (graphName != null) ? true : false;
    String dataSetEncoded = URLEncoder.encode(datasetName, "UTF-8");
    String graphEncoded = createGraph ? URLEncoder.encode(graphName, "UTF-8") : null;

    URL url = new URL(HOST + '/' + dataSetEncoded + "/data" + (createGraph ? "?graph=" + graphEncoded : ""));

    final HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();

    String boundary = "------------------" + System.currentTimeMillis()
            + Long.toString(Math.round(Math.random() * 1000));

    httpConnection.setUseCaches(false);
    httpConnection.setRequestMethod("POST");
    httpConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
    httpConnection.setRequestProperty("Connection", "keep-alive");
    httpConnection.setRequestProperty("Cache-Control", "no-cache");

    // set content
    httpConnection.setDoOutput(true);
    final OutputStreamWriter out = new OutputStreamWriter(httpConnection.getOutputStream());
    out.write(BOUNDARY_DECORATOR + boundary + EOL);
    out.write("Content-Disposition: form-data; name=\"files[]\"; filename=\"ontology.owl\"" + EOL);
    out.write("Content-Type: application/octet-stream" + EOL + EOL);
    out.write(CharStreams.toString(new InputStreamReader(ontology)));
    out.write(EOL + BOUNDARY_DECORATOR + boundary + BOUNDARY_DECORATOR + EOL);
    out.close();

    // handle HTTP/HTTPS strange behaviour
    httpConnection.connect();
    httpConnection.disconnect();

    // handle response
    switch (httpConnection.getResponseCode()) {
    case HttpURLConnection.HTTP_CREATED:
        checkState(createGraph, "bad state - code:" + httpConnection.getResponseCode() + " message: "
                + httpConnection.getResponseMessage());
        break;
    case HttpURLConnection.HTTP_OK:
        checkState(!createGraph, "bad state - code:" + httpConnection.getResponseCode() + " message: "
                + httpConnection.getResponseMessage());
        break;
    default:
        throw new HttpException(
                httpConnection.getResponseCode() + " message: " + httpConnection.getResponseMessage());
    }

}

From source file:i5.las2peer.services.servicePackage.TemplateService.java

/**
 * Example method that shows how to retrieve a user email address from a database 
 * and return an HTTP response including a JSON object.
 * //w w w . ja  v  a 2s . c  o m
 * WARNING: THIS METHOD IS ONLY FOR DEMONSTRATIONAL PURPOSES!!! 
 * IT WILL REQUIRE RESPECTIVE DATABASE TABLES IN THE BACKEND, WHICH DON'T EXIST IN THE TEMPLATE.
 * 
 */
@GET
@Path("/userEmail/{username}")
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "User Email"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"),
        @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "User not found"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal Server Error") })
@ApiOperation(value = "Email Address Administration", notes = "Example method that retrieves a user email address from a database."
        + " WARNING: THIS METHOD IS ONLY FOR DEMONSTRATIONAL PURPOSES!!! "
        + "IT WILL REQUIRE RESPECTIVE DATABASE TABLES IN THE BACKEND, WHICH DON'T EXIST IN THE TEMPLATE.")
public HttpResponse getUserEmail(@PathParam("username") String username) {
    String result = "";
    Connection conn = null;
    PreparedStatement stmnt = null;
    ResultSet rs = null;
    try {

        // get connection from connection pool
        conn = dbm.getConnection();

        // prepare statement
        stmnt = conn.prepareStatement("SELECT email FROM users WHERE username = ?;");
        stmnt.setString(1, username);

        // retrieve result set
        rs = stmnt.executeQuery();

        // process result set
        if (rs.next()) {
            result = rs.getString(1);

            // setup resulting JSON Object
            JSONObject ro = new JSONObject();
            ro.put("email", result);

            // return HTTP Response on success
            return new HttpResponse(ro.toString(), HttpURLConnection.HTTP_OK);
        } else {
            result = "No result for username " + username;

            // return HTTP Response on error
            return new HttpResponse(result, HttpURLConnection.HTTP_NOT_FOUND);
        }
    } catch (Exception e) {
        // return HTTP Response on error
        return new HttpResponse("Internal error: " + e.getMessage(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    } finally {
        // free resources
        if (rs != null) {
            try {
                rs.close();
            } catch (Exception e) {
                Context.logError(this, e.getMessage());

                // return HTTP Response on error
                return new HttpResponse("Internal error: " + e.getMessage(),
                        HttpURLConnection.HTTP_INTERNAL_ERROR);
            }
        }
        if (stmnt != null) {
            try {
                stmnt.close();
            } catch (Exception e) {
                Context.logError(this, e.getMessage());

                // return HTTP Response on error
                return new HttpResponse("Internal error: " + e.getMessage(),
                        HttpURLConnection.HTTP_INTERNAL_ERROR);
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (Exception e) {
                Context.logError(this, e.getMessage());

                // return HTTP Response on error
                return new HttpResponse("Internal error: " + e.getMessage(),
                        HttpURLConnection.HTTP_INTERNAL_ERROR);
            }
        }
    }
}