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.jboss.as.test.integration.web.formauth.FormAuthUnitTestCase.java

/**
 * Test that a bad login is redirected to the errors.jsp and that the
 * session j_exception is not null.//w  ww.  j a  v  a  2  s. c om
 */
@Test
@Ignore
@OperateOnDeployment("form-auth.war")
public void testFormAuthException() throws Exception {
    log.info("+++ testFormAuthException");

    URL url = new URL(baseURLNoAuth + "restricted/SecuredServlet");
    HttpGet httpget = new HttpGet(url.toURI());

    log.info("Executing request " + httpget.getRequestLine());
    HttpResponse response = httpclient.execute(httpget);

    int statusCode = response.getStatusLine().getStatusCode();
    Header[] errorHeaders = response.getHeaders("X-NoJException");
    assertTrue("Wrong response code: " + statusCode, statusCode == HttpURLConnection.HTTP_OK);
    assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0);

    HttpEntity entity = response.getEntity();
    if ((entity != null) && (entity.getContentLength() > 0)) {
        String body = EntityUtils.toString(entity);
        assertTrue("Redirected to login page", body.indexOf("j_security_check") > 0);
    } else {
        fail("Empty body in response");
    }

    String sessionID = null;
    for (Cookie k : httpclient.getCookieStore().getCookies()) {
        if (k.getName().equalsIgnoreCase("JSESSIONID"))
            sessionID = k.getValue();
    }
    log.info("Saw JSESSIONID=" + sessionID);

    // Submit the login form
    HttpPost formPost = new HttpPost(baseURLNoAuth + "j_security_check");
    formPost.addHeader("Referer", baseURLNoAuth + "restricted/login.html");

    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    formparams.add(new BasicNameValuePair("j_username", "baduser"));
    formparams.add(new BasicNameValuePair("j_password", "badpass"));
    formPost.setEntity(new UrlEncodedFormEntity(formparams, "UTF-8"));

    log.info("Executing request " + formPost.getRequestLine());
    HttpResponse postResponse = httpclient.execute(formPost);

    statusCode = postResponse.getStatusLine().getStatusCode();
    errorHeaders = postResponse.getHeaders("X-NoJException");
    assertTrue("Should see HTTP_OK. Got " + statusCode, statusCode == HttpURLConnection.HTTP_OK);
    assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is not null", errorHeaders.length != 0);
    log.debug("Saw X-JException, " + Arrays.toString(errorHeaders));
}

From source file:mobisocial.musubi.identity.AphidIdentityProvider.java

public boolean initiateTwoPhaseClaim(IBIdentity ident, String key, int requestId) {
    // Send the request to Aphid
    HttpClient http = new CertifiedHttpClient(mContext);
    List<NameValuePair> qparams = new ArrayList<NameValuePair>();
    qparams.add(new BasicNameValuePair("req", new Integer(requestId).toString()));
    qparams.add(new BasicNameValuePair("type", new Integer(ident.authority_.ordinal()).toString()));
    qparams.add(new BasicNameValuePair("uid", ident.principal_));
    qparams.add(new BasicNameValuePair("time", new Long(ident.temporalFrame_).toString()));
    qparams.add(new BasicNameValuePair("key", key));
    try {//  w  ww  .ja v a 2  s .c o m
        // Send the request
        URI uri = URIUtils.createURI(URL_SCHEME, SERVER_LOCATION, -1, CLAIM_PATH,
                URLEncodedUtils.format(qparams, "UTF-8"), null);
        Log.d(TAG, "Aphid URI: " + uri.toString());
        HttpGet httpGet = new HttpGet(uri);
        HttpResponse response = http.execute(httpGet);
        int code = response.getStatusLine().getStatusCode();

        // Read the response
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String responseStr = "";
        String line = "";
        while ((line = rd.readLine()) != null) {
            responseStr += line;
        }
        Log.d(TAG, "Server response:" + responseStr);

        // Only 200 should indicate that this worked
        if (code == HttpURLConnection.HTTP_OK) {
            // Mark as notified (suppress repeated texts)
            MIdentity mid = mIdentitiesManager.getIdentityForIBHashedIdentity(ident);
            if (mid != null) {
                MPendingIdentity pendingIdent = mPendingIdentityManager.lookupIdentity(mid.id_,
                        ident.temporalFrame_, requestId);
                if (pendingIdent == null) {
                    pendingIdent = mPendingIdentityManager.fillPendingIdentity(mid.id_, ident.temporalFrame_);
                    mPendingIdentityManager.insertIdentity(pendingIdent);
                }
                pendingIdent.notified_ = true;
                mPendingIdentityManager.updateIdentity(pendingIdent);
            }
            return true;
        }
    } catch (URISyntaxException e) {
        Log.e(TAG, "URISyntaxException", e);
    } catch (IOException e) {
        Log.i(TAG, "Error claiming keys.");
    }
    return false;
}

From source file:UploadTest.java

@Test
public void test_upload_data() {
    try {/*  www .  j  av a  2 s  .  c  o  m*/

        try {
            url = new URL("https://api.localhost/resource/frl:6376979/data");
            httpCon = (HttpsURLConnection) url.openConnection();
            String userpass = user + ":" + password;
            basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
            httpCon.setRequestProperty("Authorization", basicAuth);
        } catch (Exception e) {
            e.printStackTrace();
        }

        List<String> response = new ArrayList<String>();
        httpCon.setRequestProperty("Content-Type", "application/json");
        httpCon.setRequestProperty("Accept", "application/json");
        httpCon.setDoOutput(true);
        httpCon.setRequestMethod("PUT");
        httpCon.setReadTimeout(5000);
        String content = "{\"contentType\":\"monograph\",\"accessScheme\":\"public\",\"publishScheme\":\"public\"}";
        try (OutputStreamWriter out = new OutputStreamWriter(httpCon.getOutputStream())) {
            out.write(content);
        }
        System.out.println("HELLO");
        // System.out.println(httpCon.getResponseCode());

        httpCon.getInputStream();
        System.out.println("HELLO");
        int status = httpCon.getResponseCode();
        System.out.println("HELLO");
        if (status == HttpURLConnection.HTTP_OK) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(httpCon.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                response.add(line);
            }
            reader.close();
            httpCon.disconnect();
        } else {
            throw new IOException("Server returned non-OK status: " + status);
        }

        // httpCon.disconnect();
        System.out.println("Status: " + status + "\nResponse: " + response.toString());

    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}

From source file:net.sf.okapi.filters.drupal.DrupalConnector.java

/**
 * Log in to start session/*w  w  w  .j  a v  a 2 s .c o  m*/
 * @param username
 * @param password
 * @return
 * @throws IOException
 * @throws ParseException
 */
@SuppressWarnings("unchecked")
boolean login() {
    try {
        URL url = new URL(host + "rest/user/login");
        HttpURLConnection conn = createConnection(url, "POST", true);

        JSONObject login = new JSONObject();
        login.put("username", user);
        login.put("password", pass);

        OutputStream os = conn.getOutputStream();
        os.write(login.toJSONString().getBytes());
        os.flush();

        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            conn.disconnect();
            return false;
        }

        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

        JSONParser parser = new JSONParser();
        JSONObject obj = (JSONObject) parser.parse(reader);

        session_cookie = obj.get("session_name") + "=" + obj.get("sessid");
        conn.disconnect();
    } catch (Throwable e) {
        throw new OkapiIOException("Error in login().", e);
    }
    return true;
}

From source file:org.jboss.as.test.integration.web.sso.SSOTestBase.java

public static void checkAccessDenied(HttpClient httpConn, String url) throws IOException {
    HttpGet getMethod = new HttpGet(url);
    HttpResponse response = httpConn.execute(getMethod);

    int statusCode = response.getStatusLine().getStatusCode();
    assertTrue("Expected code == OK but got " + statusCode + " for request=" + url,
            statusCode == HttpURLConnection.HTTP_OK);

    String body = EntityUtils.toString(response.getEntity());
    assertTrue("Redirected to login page for request=" + url + ", body[" + body + "]",
            body.indexOf("j_security_check") > 0);
}

From source file:mobi.jenkinsci.ci.JenkinsCIPlugin.java

protected byte[] retrieveUrl(final String userAgent, final String linkUrl,
        final HashMap<String, HeaderElement[]> contentHeaders, final Object ctx) throws Exception {
    final JenkinsClient client = (JenkinsClient) ctx;
    final HttpRequestBase get = getNewHttpRequest(null, linkUrl);
    if (userAgent != null) {
        get.setHeader("User-Agent", userAgent);
    }/* w  w w .  j a  va 2s.c  om*/
    final HttpResponse response = client.http.execute(get);
    try {
        final int status = response.getStatusLine().getStatusCode();
        if (status != HttpURLConnection.HTTP_OK) {
            throw new IOException("HTTP- " + get.getMethod() + " " + linkUrl + " returned status " + status);
        }

        if (contentHeaders != null) {
            for (final Header header : response.getAllHeaders()) {
                contentHeaders.put(header.getName(), header.getElements());
            }
        }

        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        final InputStream content = response.getEntity().getContent();
        IOUtils.copy(content, out);
        content.close();
        return out.toByteArray();
    } finally {
        get.releaseConnection();
    }
}

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

public static ResponseObject registerDeviceId(String deviceId, String token) {
    JSONObject jsonObj = null;//  ww  w. j  a  va  2 s . c o m
    int statusCode = 0;

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

    String reqUrl = serverUrl + "/gcm/";
    Log.i(TAG, "submit url=" + reqUrl);

    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);
        }

        JSONObject data = new JSONObject();
        try {
            data.put("gcmRegId", deviceId);
        } catch (JSONException e) {
            Log.e(TAG, "Error while create json object", e);
        }

        post.setEntity(new StringEntity(data.toString(), 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) {
            InputStream in = entity.getContent();
            String resp = FileUtil.convertInputStreamToString(in);
            Log.d(TAG, "Register device id : Response text= " + resp);
            jsonObj = new JSONObject();
            entity.consumeContent();
        }

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

From source file:org.eclipse.hono.deviceregistry.FileBasedTenantService.java

private TenantResult<JsonObject> getForCertificateAuthority(final X500Principal subjectDn) {

    if (subjectDn == null) {
        return TenantResult.from(HttpURLConnection.HTTP_BAD_REQUEST);
    } else {/*from  ww w.j av  a 2 s. co m*/
        final TenantObject tenant = getByCa(subjectDn);

        if (tenant == null) {
            return TenantResult.from(HttpURLConnection.HTTP_NOT_FOUND);
        } else {
            return TenantResult.from(HttpURLConnection.HTTP_OK, JsonObject.mapFrom(tenant),
                    CacheDirective.maxAgeDirective(MAX_AGE_GET_TENANT));
        }
    }
}

From source file:jetbrains.buildServer.vmgr.agent.Utils.java

public String checkVAPIConnection(String url, boolean requireAuth, String user, String password)
        throws Exception {

    String textOut = null;/*from   ww  w . j a  v  a  2  s.  c  o m*/
    try {

        System.out.println("Trying to connect with vManager vAPI " + url);
        String input = "{}";

        String apiURL = url + "/rest/sessions/count";

        HttpURLConnection conn = getVAPIConnection(apiURL, requireAuth, user, password, "POST", false, "", null,
                null);
        OutputStream os = null;
        try {
            os = conn.getOutputStream();
        } catch (java.net.UnknownHostException e) {

            throw new Exception("Failed to connect to host " + e.getMessage() + ".  Host is unknown.");

        }
        os.write(input.getBytes());
        os.flush();

        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            String reason = "";
            if (conn.getResponseCode() == 503)
                reason = "vAPI process failed to connect to remote vManager server.";
            if (conn.getResponseCode() == 401)
                reason = "Authentication Error";
            if (conn.getResponseCode() == 412)
                reason = "vAPI requires vManager 'Integration Server' license.";
            String errorMessage = "Failed : HTTP error code : " + conn.getResponseCode() + " (" + reason + ")";

            return errorMessage;
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

        StringBuilder result = new StringBuilder();
        String output;

        while ((output = br.readLine()) != null) {
            result.append(output);
        }

        conn.disconnect();

        JSONObject tmp = JSONObject.fromObject(result.toString());

        textOut = " The current number of sessions held on this vManager server are: " + tmp.getString("count");

    } catch (Exception e) {

        String errorMessage = "Failed : HTTP error: " + e.getMessage();

        if (e.getMessage().indexOf("Unexpected end of file from server") > -1) {
            errorMessage = errorMessage
                    + " (from Incisive 14.2 onward the connection is secured.  Verify your url is https://)";
        }

        System.out.println(errorMessage);
        textOut = errorMessage;
    }

    return textOut;
}