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:i5.las2peer.services.test.Test.java

/**
 * /* w  w w  . j ava 2  s  .com*/
 * test
 * 
 *
 * 
 * @return HttpResponse  
 * 
 */
@GET
@Path("/est")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.TEXT_PLAIN)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "test") })
@ApiOperation(value = "test", notes = " ")
public HttpResponse test() {
    Serializable test = null;

    try {
        Object test = this.invokeServiceMethod("test", "test", test);
    } catch (Exception e) {
        e.printStackTrace();
    }
    // test
    boolean test_condition = true;
    if (test_condition) {
        JSONObject etst2 = new JSONObject();
        HttpResponse test = new HttpResponse(etst2.toJSONString(), HttpURLConnection.HTTP_OK);
        return test;
    }
    return null;
}

From source file:net.sf.ehcache.constructs.web.filter.GzipFilterTest.java

/**
 * Tests that a page which is storeGzipped is gzipped when the user agent accepts gzip encoding
 *///from www.  java2s. com
public void testGzippedWhenAcceptEncodingHomePage() throws Exception {
    WebConversation client = createWebConversation(true);
    client.getClientProperties().setAcceptGzip(true);
    String url = buildUrl("/GzipOnlyPage.jsp");
    WebResponse response = client.getResponse(url);

    assertNotNull(response);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    String responseURL = response.getURL().toString();
    assertEquals(url, responseURL);
    assertEquals("gzip", response.getHeaderField("Content-Encoding"));

    //Check that we are dealing with Cyrillic characters ok
    assertTrue(response.getText().indexOf("↑") != -1);
    //Check non ascii symbol
    assertTrue(response.getText().indexOf("М") != -1);
}

From source file:io.apiman.cli.PluginTest.java

/**
 * @return the plugin expected to have been added
 * @throws java.io.IOException// w ww.ja v  a  2s  . com
 */
@NotNull
private Plugin getPlugin() throws java.io.IOException {
    // fetch all plugins
    final Response response = given().log().all()
            .header(AuthUtil.HEADER_AUTHORIZATION, AuthUtil.BASIC_AUTH_VALUE).when().get("/plugins")
            .thenReturn();

    assertEquals(HttpURLConnection.HTTP_OK, response.statusCode());

    @SuppressWarnings("unchecked")
    final List<Plugin> plugins = MappingUtil.JSON_MAPPER.readValue(response.body().asByteArray(),
            new TypeReference<List<Plugin>>() {
            });

    assertNotNull(plugins);
    assertTrue("At least one plugin should be installed", plugins.size() > 0);

    // find the expected plugin
    final Optional<Plugin> addedPlugin = plugins.stream().filter(this::isArtifactMatch).findAny();

    assertTrue(addedPlugin.isPresent());
    return addedPlugin.get();
}

From source file:de.unidue.inf.is.ezdl.dlservices.library.manager.referencesystems.connotea.ConnoteaUtils.java

/** send a GET Request and return the response as string */
String sendGetRequest(String url) throws Exception {
    String sresponse;/* ww  w.j  a v a 2  s.c  o m*/
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(url);

    // set authentication header
    httpget.addHeader("Authorization", authHeader);

    HttpResponse response = httpclient.execute(httpget);

    // Check status code
    if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
        HttpEntity entity = response.getEntity();
        sresponse = readResponseStream(entity.getContent());
        httpclient.getConnectionManager().shutdown();
    } else {
        HttpEntity entity = response.getEntity();
        sresponse = readResponseStream(entity.getContent());

        String httpcode = Integer.toString(response.getStatusLine().getStatusCode());
        httpclient.getConnectionManager().shutdown();
        throw new ReferenceSystemException(httpcode, "Connotea Error", RDFUtils.parseError(sresponse));
    }
    return sresponse;
}

From source file:com.example.austin.test.TextActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_text);

    Thread thread = new Thread(new Runnable() {
        @Override// w w w  . j  ava  2 s . c  o m
        public void run() {
            try {
                Bundle bundle = getIntent().getExtras();
                Bitmap photo = (Bitmap) bundle.get("photo");
                ByteArrayOutputStream stream1 = new ByteArrayOutputStream();
                photo.compress(Bitmap.CompressFormat.PNG, 100, stream1);
                byte[] fileContent = stream1.toByteArray();

                String license_code = "59D1D7B4-61FD-49EB-A549-C77E08B7103A";
                String user_name = "austincheng16";

                String ocrURL = "http://www.ocrwebservice.com/restservices/processDocument?gettext=true";
                URL url = new URL(ocrURL);

                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoOutput(true);
                connection.setDoInput(true);
                connection.setRequestMethod("POST");

                connection.setRequestProperty("Authorization", "Basic "
                        + new String(Base64.encodeBase64((user_name + ":" + license_code).getBytes())));

                connection.setRequestProperty("Content-Type", "application/json");

                connection.setRequestProperty("Content-Length", Integer.toString(fileContent.length));

                try {
                    OutputStream stream = connection.getOutputStream();

                    stream.write(fileContent);
                    stream.close();

                    int httpCode = connection.getResponseCode();

                    if (httpCode == HttpURLConnection.HTTP_OK) {
                        String jsonResponse = GetResponseToString(connection.getInputStream());
                        PrintOCRResponse(jsonResponse);
                    } else {
                        String jsonResponse = GetResponseToString(connection.getErrorStream());
                        JSONParser parser = new JSONParser();
                        JSONObject jsonObj = (JSONObject) parser.parse(jsonResponse);
                        Log.i("austin", "Error Message: " + jsonObj.get("ErrorMessage"));
                    }
                    connection.disconnect();
                } catch (IOException e) {
                    Log.i("austin", "IOException");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    thread.start();
}

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

@Override
public ResponseToProcess execute(ProcessedAPIRequest request, SDKServiceProvider serviceProvider) {
    LoggerService logger = serviceProvider.getLoggerService(ReadParams.class);
    Map<String, String> errMap = new HashMap<String, String>();

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

    JSONParser parser = new JSONParser();

    try {/*from   w  w w.  j  ava 2  s.c o m*/
        Object obj = parser.parse(request.getBody());
        JSONObject jsonObject = (JSONObject) obj;

        // Find the values you are looking for
        model = (String) jsonObject.get("model");
        make = (String) jsonObject.get("make");
        year = (String) jsonObject.get("year");
    } catch (ParseException pe) {
        // Log your error
        logger.error(pe.getMessage(), pe);
        return Util.badRequestResponse(errMap, "Error Parsing Input");
    }

    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:de.intevation.irix.PrintClient.java

/** Obtains a Report from mapfish-print service.
 *
 * @param printUrl The url to send the request to.
 * @param json The json spec for the print request.
 * @param timeout the timeout for the httpconnection.
 *
 * @return byte[] with the report./*from  w  w  w  . j  a va2 s . com*/
 *
 * @throws IOException if communication with print service failed.
 * @throws PrintException if the print job failed.
 */
public static byte[] getReport(String printUrl, String json, int timeout) throws IOException, PrintException {

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

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

    HttpEntity entity = new StringEntity(json,
            ContentType.create("application/json", Charset.forName("UTF-8")));

    HttpPost post = new HttpPost(printUrl);
    post.setEntity(entity);
    CloseableHttpResponse resp = client.execute(post);

    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 PrintException(new String(retval));
        } else {
            throw new PrintException("Communication with print service '" + printUrl + "' failed."
                    + "\nNo response from print service.");
        }
    }
    return retval;
}

From source file:zz.pseas.ghost.login.weibo.SinaWeiboLogin.java

public static String getSinaCookie(String username, String password) throws Exception {

    StringBuilder sb = new StringBuilder();
    HtmlUnitDriver driver = new HtmlUnitDriver(true);
    // driver.setSocksProxy("127.0.0.1", 1080);
    // driver.setProxy("127.0.0.1", 1080);
    // HtmlOption htmlOption=new Ht
    // WebDriver driver = new FirefoxDriver();
    driver.setJavascriptEnabled(true);/*from w w  w .jav a  2s  . com*/
    // user agent switcher//
    String loginAddress = "http://login.weibo.cn/login/";
    driver.get(loginAddress);
    WebElement ele = driver.findElementByCssSelector("img");
    String src = ele.getAttribute("src");
    String cookie = concatCookie(driver);

    CloseableHttpClient httpclient = HttpClients.createDefault();
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1000).setConnectTimeout(1000)
            .setCookieSpec(cookie).build();

    HttpGet httpget = new HttpGet(src);
    httpget.setConfig(requestConfig);
    CloseableHttpResponse response = httpclient.execute(httpget);

    HttpEntity entity;
    String result = null;
    try {

        if (response.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_OK) {
            // try again//
        }
        entity = response.getEntity();

        if (entity != null) {
            InputStream instream = entity.getContent();
            try {
                // do something useful
                InputStream inputStream = entity.getContent();
                BufferedImage img = ImageIO.read(inputStream);
                // deal with the weibo captcha //
                String picName = LoginUtils.getCurrentTime("yyyyMMdd-hhmmss");
                // captcha//
                LoginUtils.getCaptchaDir();
                picName = "./captcha/captcha-" + picName + ".png";
                ImageIO.write(img, "png", new File(picName));
                String userInput = new CaptchaFrame(img).getUserInput();
                WebElement mobile = driver.findElementByCssSelector("input[name=mobile]");
                mobile.sendKeys(username);
                WebElement pass = driver.findElementByCssSelector("input[name^=password]");
                pass.sendKeys(password);
                WebElement code = driver.findElementByCssSelector("input[name=code]");
                code.sendKeys(userInput);
                WebElement rem = driver.findElementByCssSelector("input[name=remember]");
                rem.click();
                WebElement submit = driver.findElementByCssSelector("input[name=submit]");
                // ?//
                submit.click();
                result = concatCookie(driver);
                driver.close();
            } finally {
                instream.close();
            }
        }
    } finally {
        response.close();
    }

    if (result.contains("gsid_CTandWM")) {
        return result;
    } else {
        // throw new Exception("weibo login failed");
        return null;
    }
}

From source file:de.unidue.inf.is.ezdl.dlservices.library.manager.referencesystems.bibsonomy.BibsonomyUtils.java

/** send a GET Request and return the response as string */
String sendGetRequest(String url) throws Exception {
    String sresponse;/*from w w  w .java2 s. c o m*/
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(url);

    // set authentification header
    httpget.addHeader("Authorization", authHeader);

    HttpResponse response = httpclient.execute(httpget);

    // check status code
    if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
        HttpEntity entity = response.getEntity();
        sresponse = readResponseStream(entity.getContent());
        httpclient.getConnectionManager().shutdown();
    } else {
        HttpEntity entity = response.getEntity();
        sresponse = readResponseStream(entity.getContent());
        String httpcode = Integer.toString(response.getStatusLine().getStatusCode());
        httpclient.getConnectionManager().shutdown();
        throw new ReferenceSystemException(httpcode, "Bibsonomy Error", XMLUtils.parseError(sresponse));
    }
    return sresponse;
}

From source file:honeypot.services.WepawetServiceImpl.java

/**
 * {@inheritDoc}/*from   w w w.j a  va 2 s.c om*/
 * @see honeypot.services.WepawetService#checkQueue(java.lang.String)
 */
@Transactional
public void checkQueue(String hash) {
    try {
        String parameters = "resource_type=js&hash=" + URLEncoder.encode(hash, "UTF-8");
        URL url = new URL("http://wepawet.cs.ucsb.edu/services/query.php?" + parameters);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setDoOutput(true);
        connection.setRequestMethod("GET");

        //Send request
        connection.connect();
        if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) {
            InputStream is = connection.getInputStream();
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            int data;
            while ((data = is.read()) != -1) {
                os.write(data);
            }
            is.close();
            // Process the XML message.
            handleQueryMsg(new ByteArrayInputStream(os.toByteArray()), hash);
            os.close();
        }
        connection.disconnect();
    } catch (final Exception e) {
        log.error("Exception occured querying the hash.", e);
        WepawetError wepawetError = new WepawetError();
        wepawetError.setCode("-1");
        wepawetError.setMessage(e.getMessage());
        wepawetError.setCreated(new Date());
        // Save the error to the database.
        entityManager.persist(wepawetError);
    }

}