List of usage examples for java.net HttpURLConnection HTTP_OK
int HTTP_OK
To view the source code for java.net HttpURLConnection HTTP_OK.
Click Source Link
From source file:com.streamsets.datacollector.http.TestLogServlet.java
@Test public void testLogs() throws Exception { String baseLogUrl = startServer() + "/rest/v1/system/logs"; try {//from w w w .j a va 2 s .c om HttpURLConnection conn = (HttpURLConnection) new URL(baseLogUrl + "/files").openConnection(); Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode()); Assert.assertTrue(conn.getContentType().startsWith("application/json")); List list = ObjectMapperFactory.get().readValue(conn.getInputStream(), List.class); Assert.assertEquals(2, list.size()); for (int i = 0; i < 2; i++) { Map map = (Map) list.get(i); String log = (String) map.get("file"); if (log.equals("test.log")) { Assert.assertEquals(logFile.lastModified(), (long) map.get("lastModified")); } else { Assert.assertEquals(oldLogFile.lastModified(), (long) map.get("lastModified")); } } conn = (HttpURLConnection) new URL(baseLogUrl + "/files/" + oldLogFile.getName()).openConnection(); Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode()); Assert.assertTrue(conn.getContentType().startsWith("text/plain")); List<String> lines = IOUtils.readLines(conn.getInputStream()); Assert.assertEquals(1, lines.size()); Assert.assertEquals("bye", lines.get(0)); } finally { stopServer(); } }
From source file:be.cytomine.client.HttpClient.java
public int get(String url, String dest) throws IOException { log.debug("get:" + url); URL URL = new URL(url); HttpHost targetHost = new HttpHost(URL.getHost(), URL.getPort()); log.debug("targetHost:" + targetHost); DefaultHttpClient client = new DefaultHttpClient(); log.debug("client:" + client); // Add AuthCache to the execution context BasicHttpContext localcontext = new BasicHttpContext(); log.debug("localcontext:" + localcontext); headersArray = null;/* www . j a v a2 s . c o m*/ authorize("GET", URL.toString(), "", "application/json,*/*"); HttpGet httpGet = new HttpGet(URL.getPath()); httpGet.setHeaders(headersArray); HttpResponse response = client.execute(targetHost, httpGet, localcontext); int code = response.getStatusLine().getStatusCode(); log.info("url=" + url + " is " + code + "(OK=" + HttpURLConnection.HTTP_OK + ",MOVED=" + HttpURLConnection.HTTP_MOVED_TEMP + ")"); boolean isOK = (code == HttpURLConnection.HTTP_OK); boolean isFound = (code == HttpURLConnection.HTTP_MOVED_TEMP); boolean isErrorServer = (code == HttpURLConnection.HTTP_INTERNAL_ERROR); if (!isOK && !isFound & !isErrorServer) { throw new IOException(url + " cannot be read: " + code); } HttpEntity entity = response.getEntity(); if (entity != null) { entity.writeTo(new FileOutputStream(dest)); } return code; }
From source file:com.nhncorp.lucy.security.xss.listener.SecurityUtils.java
public static String getContentTypeFromUrlConnection(String strUrl, ContentTypeCacheRepo contentTypeCacheRepo) { // cache ? ?. String result = contentTypeCacheRepo.getContentTypeFromCache(strUrl); //System.out.println("getContentTypeFromCache : " + result); if (StringUtils.isNotEmpty(result)) { return result; }//from w ww . j a v a 2 s . c om HttpURLConnection con = null; try { URL url = new URL(strUrl); con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("HEAD"); con.setConnectTimeout(1000); con.setReadTimeout(1000); con.connect(); int resCode = con.getResponseCode(); if (resCode != HttpURLConnection.HTTP_OK) { System.err.println("error"); } else { result = con.getContentType(); //System.out.println("content-type from response header: " + result); if (result != null) { contentTypeCacheRepo.addContentTypeToCache(strUrl, new ContentType(result, new Date())); } } } catch (Exception e) { e.printStackTrace(); } finally { if (con != null) { con.disconnect(); } } return result; }
From source file:net.bible.service.common.CommonUtils.java
/** return true if URL is accessible * //from ww w . j a v a 2s .com * 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); 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:org.jboss.as.test.integration.web.sso.SSOTestBase.java
public static void checkAccessAllowed(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("Get of " + url + " redirected to login page", body.indexOf("j_security_check") < 0); }
From source file:de.unidue.inf.is.ezdl.dlservices.library.manager.referencesystems.bibsonomy.BibsonomyUtils.java
/** send DELETE REQUEST */ String sendDeleteRequest(String url) throws Exception { String sresponse;/*ww w. j a v a2 s. c o m*/ try { HttpClient httpclient = new DefaultHttpClient(); HttpDelete httpdelete = new HttpDelete(url); // add authorization header httpdelete.addHeader("Authorization", authHeader); HttpResponse response = httpclient.execute(httpdelete); // Check status code if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK || response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_NO_CONTENT) { if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_NO_CONTENT) { sresponse = ""; } else { 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", JSONUtils.parseError(sresponse)); } } catch (UnknownHostException e) { throw new ReferenceSystemException("", "Unknow Host Exception", e.toString()); } return sresponse; }
From source file:net.praqma.jenkins.rqm.request.RQMHttpClient.java
public int login() throws HttpException, IOException, GeneralSecurityException { log.finest("Register trusting ssl"); registerTrustingSSL();/*from ww w . j a v a 2 s .c o m*/ GetMethod methodPart1 = new GetMethod(url.toString() + contextRoot + "/auth/authrequired"); int response = executeMethod(methodPart1); followRedirects(methodPart1, response); GetMethod methodPart2 = new GetMethod(this.url.toString() + contextRoot + "/authenticated/identity"); response = executeMethod(methodPart2); followRedirects(methodPart2, response); HttpMethodBase authenticationMethod = null; Header authenticateHeader = methodPart2.getResponseHeader("WWW-Authenticate"); //$NON-NLS-1$ if ((response == HttpURLConnection.HTTP_UNAUTHORIZED) && (authenticateHeader != null) && (authenticateHeader.getValue().toLowerCase().indexOf("basic realm") == 0)) { super.getState().setCredentials(new AuthScope(host, port), new UsernamePasswordCredentials(getUsr(), getPassword())); String authMethod = this.url.toString() + "/authenticated/identity"; authenticationMethod = new GetMethod(authMethod); response = super.executeMethod(methodPart2); } else { authenticationMethod = new PostMethod(this.url.toString() + contextRoot + "/j_security_check"); NameValuePair[] nvps = new NameValuePair[2]; nvps[0] = new NameValuePair("j_username", getUsr()); nvps[1] = new NameValuePair("j_password", getPassword()); ((PostMethod) (authenticationMethod)).addParameters(nvps); ((PostMethod) (authenticationMethod)).addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); response = executeMethod(authenticationMethod); Header location = authenticationMethod.getResponseHeader("X-com-ibm-team-repository-web-auth-msg"); if (location != null && location.getValue().indexOf("authfailed") >= 0) { response = HttpURLConnection.HTTP_UNAUTHORIZED; } } if ((response != HttpURLConnection.HTTP_OK) && (response != HttpURLConnection.HTTP_MOVED_TEMP)) { if (response != HttpURLConnection.HTTP_UNAUTHORIZED) { String body = ""; try { body = authenticationMethod.getResponseBodyAsString(); } catch (Exception e) { log.severe(String.format("Failed to login, with response code %s %n Response body: %n %s", response, body)); } log.severe(String.format("Failed to login, with response code %s %n Response body: %n %s", response, body)); } } else { followRedirects(authenticationMethod, response); String methodText = String.format( "%s%s/service/com.ibm.team.repository.service.internal.webuiInitializer.IWebUIInitializerRestService/initializationData", url.toString(), contextRoot); GetMethod get3 = new GetMethod(methodText); response = executeMethod(get3); followRedirects(get3, response); } log.finest("Response was: " + response); return response; }
From source file:i5.las2peer.services.userManagement.UserManagement.java
/** * // www . j av a2 s . com * updateUser * * * @return HttpResponse * */ @PUT @Path("/update") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.TEXT_PLAIN) @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "userNotFound"), @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "updated"), @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "malformedUpdate") }) @ApiOperation(value = "updateUser", notes = "") public HttpResponse updateUser() { // userNotFound boolean userNotFound_condition = true; if (userNotFound_condition) { String error = "Some String"; HttpResponse userNotFound = new HttpResponse(error, HttpURLConnection.HTTP_NOT_FOUND); return userNotFound; } // updated boolean updated_condition = true; if (updated_condition) { JSONObject updatedUser = new JSONObject(); HttpResponse updated = new HttpResponse(updatedUser.toJSONString(), HttpURLConnection.HTTP_OK); return updated; } // malformedUpdate boolean malformedUpdate_condition = true; if (malformedUpdate_condition) { String error = "Some String"; HttpResponse malformedUpdate = new HttpResponse(error, HttpURLConnection.HTTP_BAD_REQUEST); return malformedUpdate; } return null; }
From source file:io.confluent.kafka.schemaregistry.client.rest.RestService.java
/** * @param requestUrl HTTP connection will be established with this url. * @param method HTTP method ("GET", "POST", "PUT", etc.) * @param requestBodyData Bytes to be sent in the request body. * @param requestProperties HTTP header properties. * @param responseFormat Expected format of the response to the HTTP request. * @param <T> The type of the deserialized response to the HTTP request. * @return The deserialized response to the HTTP request, or null if no data is expected. *//*from ww w . j a va 2s . com*/ private <T> T sendHttpRequest(String requestUrl, String method, byte[] requestBodyData, Map<String, String> requestProperties, TypeReference<T> responseFormat) throws IOException, RestClientException { log.debug(String.format("Sending %s with input %s to %s", method, requestBodyData == null ? "null" : new String(requestBodyData), requestUrl)); HttpURLConnection connection = null; try { URL url = new URL(requestUrl); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(method); // connection.getResponseCode() implicitly calls getInputStream, so always set to true. // On the other hand, leaving this out breaks nothing. connection.setDoInput(true); for (Map.Entry<String, String> entry : requestProperties.entrySet()) { connection.setRequestProperty(entry.getKey(), entry.getValue()); } connection.setUseCaches(false); if (requestBodyData != null) { connection.setDoOutput(true); OutputStream os = null; try { os = connection.getOutputStream(); os.write(requestBodyData); os.flush(); } catch (IOException e) { log.error("Failed to send HTTP request to endpoint: " + url, e); throw e; } finally { if (os != null) os.close(); } } int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream is = connection.getInputStream(); T result = jsonDeserializer.readValue(is, responseFormat); is.close(); return result; } else if (responseCode == HttpURLConnection.HTTP_NO_CONTENT) { return null; } else { InputStream es = connection.getErrorStream(); ErrorMessage errorMessage; try { errorMessage = jsonDeserializer.readValue(es, ErrorMessage.class); } catch (JsonProcessingException e) { errorMessage = new ErrorMessage(JSON_PARSE_ERROR_CODE, e.getMessage()); } es.close(); throw new RestClientException(errorMessage.getMessage(), responseCode, errorMessage.getErrorCode()); } } finally { if (connection != null) { connection.disconnect(); } } }
From source file:org.eclipse.mylyn.internal.bugzilla.rest.core.BugzillaRestPostNewTask.java
@Override protected void doValidate(CommonHttpResponse response, IOperationMonitor monitor) throws IOException, BugzillaRestException { int statusCode = response.getStatusCode(); if (statusCode != HttpURLConnection.HTTP_BAD_REQUEST && statusCode != HttpURLConnection.HTTP_OK) { if (statusCode == HttpStatus.SC_NOT_FOUND) { throw new BugzillaRestResourceNotFoundException( NLS.bind("Requested resource ''{0}'' does not exist", response.getRequestPath())); }//from w ww .j a va2s. co m throw new BugzillaRestException( NLS.bind("Unexpected response from Bugzilla REST server for ''{0}'': {1}", response.getRequestPath(), HttpUtil.getStatusText(statusCode))); } }