List of usage examples for org.apache.commons.httpclient HttpStatus SC_OK
int SC_OK
To view the source code for org.apache.commons.httpclient HttpStatus SC_OK.
Click Source Link
From source file:be.fedict.trust.service.util.ClockDriftUtil.java
public static Date executeTSP(ClockDriftConfigEntity clockDriftConfig, NetworkConfig networkConfig) throws IOException, TSPException { LOG.debug("clock drift detection: " + clockDriftConfig.toString()); TimeStampRequestGenerator requestGen = new TimeStampRequestGenerator(); TimeStampRequest request = requestGen.generate(TSPAlgorithms.SHA1, new byte[20], BigInteger.valueOf(100)); byte[] requestData = request.getEncoded(); HttpClient httpClient = new HttpClient(); if (null != networkConfig) { httpClient.getHostConfiguration().setProxy(networkConfig.getProxyHost(), networkConfig.getProxyPort()); }//from w w w . j ava 2 s .c o m PostMethod postMethod = new PostMethod(clockDriftConfig.getServer()); postMethod.setRequestEntity(new ByteArrayRequestEntity(requestData, "application/timestamp-query")); int statusCode = httpClient.executeMethod(postMethod); if (statusCode != HttpStatus.SC_OK) { throw new TSPException("Error contacting TSP server " + clockDriftConfig.getServer()); } TimeStampResponse tspResponse = new TimeStampResponse(postMethod.getResponseBodyAsStream()); postMethod.releaseConnection(); return tspResponse.getTimeStampToken().getTimeStampInfo().getGenTime(); }
From source file:com.ifeng.vdn.ip.repository.service.impl.BaiduBatchIPAddressChecker.java
@Override public List<BaiduIPBean> check(List<String> ips) { List<BaiduIPBean> list = new ArrayList<BaiduIPBean>(); BaiduIPBean ipaddress = null;/*from w w w.j a v a 2s . c om*/ // Create an instance of HttpClient. HttpClient clinet = new HttpClient(); for (String ip : ips) { String url = "https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query=" + ip + "&co=&resource_id=6006&t=1428632527853&ie=utf8&oe=gbk&cb=op_aladdin_callback&format=json&tn=baidu&cb=jQuery110204891062709502876_1428631554303&_=1428631554305"; // Create a method instance. GetMethod getMethod = new GetMethod(url); try { // Execute the method. int statusCode = clinet.executeMethod(getMethod); if (statusCode != HttpStatus.SC_OK) { log.error("Method failedd: {}", getMethod.getStatusCode()); } else { // Read the response body. byte[] responseBody = getMethod.getResponseBody(); String responseStr = new String(responseBody, "GBK"); responseStr = responseStr.substring(responseStr.indexOf("(") + 1, responseStr.indexOf(")")); ObjectMapper mapper = new ObjectMapper(); ipaddress = mapper.readValue(responseStr, BaiduIPBean.class); list.add(ipaddress); } } catch (JsonParseException | JsonMappingException | HttpException e) { log.error(e.getMessage(), e); } catch (IOException e) { log.error(e.getMessage(), e); } } return list; }
From source file:cn.edu.seu.herald.auth.AuthenticationServiceImpl.java
@Override public StudentUser authenticate(String username, String password) throws AuthenticationServiceException { PostMethod post = new PostMethod(baseUri); post.setQueryString(new NameValuePair[] { new NameValuePair(PARAM_USER, username), new NameValuePair(PARAM_PASS, password) }); try {// w w w .j av a 2 s .c om int statusCode = httpClient.executeMethod(post); if (statusCode == HttpStatus.SC_UNAUTHORIZED) { return null; } if (statusCode != HttpStatus.SC_OK) { throw new AuthenticationServiceException("Unexpected status: " + statusCode); } String csv = post.getResponseBodyAsString(); String values[] = csv.split(","); if (values == null || values.length != 2) { throw new AuthenticationServiceException( String.format("%s\n%s\n", "Unexpected server response:\n", csv)); } String name = values[0]; String cardNumber = values[1]; return new StudentUser(name, cardNumber); } catch (IOException ex) { throw new AuthenticationServiceException(ex); } finally { post.releaseConnection(); } }
From source file:it.geosolutions.geonetwork.op.GNMetadataDelete.java
private static void gnDeleteMetadata(HTTPUtils connection, String baseURL, final Element gnRequest) throws GNServerException { String serviceURL = baseURL + "/srv/en/xml.metadata.delete"; gnPost(connection, serviceURL, gnRequest); if (connection.getLastHttpStatus() != HttpStatus.SC_OK) throw new GNServerException("Error deleting metadata in GeoNetwork"); }
From source file:com.braindrainpain.docker.httpsupport.HttpClientService.java
public void checkConnection(String url) { LOG.debug("Checking: '" + url + "'"); try {/*from ww w .java2 s. c o m*/ URI uri = new URI(url, false); this.getMethod.setURI(uri); getMethod.setFollowRedirects(false); int status = httpClient.executeMethod(getMethod); if (status != HttpStatus.SC_OK) { LOG.error("Not ok from: '" + url + "'"); LOG.error("status: " + status); throw new RuntimeException("Not ok from: '" + url + "'"); } } catch (IOException e) { LOG.error("Error connecting to: '" + url + "'"); throw new RuntimeException("Error connecting to: '" + url + "'"); } }
From source file:com.criticalsoftware.mobics.presentation.util.GeolocationUtil.java
/** * Get the full address name//from ww w. java 2 s . c om * * @param latitude * @param longitude * @return address string */ public static String getAddressFromCoordinates(String latitude, String longitude) { String address = null; String url = MessageFormat.format(GEOLOCATION_URL, Configuration.INSTANCE.getGeolocationServer(), latitude, longitude); HttpMethod method = new GetMethod(url); try { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Making reverse geolocation call to: {}", url); } int statusCode = new HttpClient().executeMethod(method); if (statusCode == HttpStatus.SC_OK) { byte[] responseBody = readResponse(method); JSONObject jsonObject = (JSONObject) new JSONParser().parse(new String(responseBody)); if (LOGGER.isTraceEnabled()) { LOGGER.trace(jsonObject.toJSONString()); } address = getFormattedAddress(jsonObject); } else { LOGGER.warn("Recived a HTTP status {}. Response was not good from {}", statusCode, url); } } catch (HttpException e) { LOGGER.error("Error while making call.", e); } catch (IOException e) { LOGGER.error("Error while reading the response.", e); } catch (ParseException e) { LOGGER.error("Error while parsing json response.", e); } return address; }
From source file:ensen.controler.AnnotationClient.java
public String request(HttpMethod method) throws AnnotationException { String response = null;// w w w. j a v a 2 s. co m // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); try { // Execute the method. client.setHttpConnectionManager(new MultiThreadedHttpConnectionManager()); int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { System.out.println("Method failed: " + method.getStatusLine()); } // Read the response body. InputStream responseBodyStream = method.getResponseBodyAsStream(); //Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended. int b = responseBodyStream.read(); ArrayList<Integer> bytes = new ArrayList<Integer>(); while (b != -1) { bytes.add(b); b = responseBodyStream.read(); } byte[] responseBody = new byte[bytes.size()]; for (int i = 0; i < bytes.size(); i++) { responseBody[i] = bytes.get(i).byteValue(); } // Deal with the response. // Use caution: ensure correct character encoding and is not binary data response = new String(responseBody); } catch (HttpException e) { System.out.println("Fatal protocol violation: " + e.getMessage()); try { System.err.println(method.getURI()); } catch (URIException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } throw new AnnotationException("Protocol error executing HTTP request.", e); } catch (IOException e) { System.out.println("Fatal transport error: " + e.getMessage()); System.out.println(method.getQueryString()); throw new AnnotationException("Transport error executing HTTP request.", e); } finally { // Release the connection. method.releaseConnection(); } return response; }
From source file:com.owncloud.android.lib.resources.users.GetPrivateKeyOperation.java
/** * @param client Client object/* www . j a v a 2 s . c om*/ */ @Override protected RemoteOperationResult run(OwnCloudClient client) { GetMethod getMethod = null; RemoteOperationResult result; try { // remote request getMethod = new GetMethod(client.getBaseUri() + PUBLIC_KEY_URL + JSON_FORMAT); getMethod.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE); int status = client.executeMethod(getMethod, SYNC_READ_TIMEOUT, SYNC_CONNECTION_TIMEOUT); if (status == HttpStatus.SC_OK) { ServerResponse<PrivateKey> serverResponse = getServerResponse(getMethod, new TypeToken<ServerResponse<PrivateKey>>() { }); result = new RemoteOperationResult(true, getMethod); ArrayList<Object> keys = new ArrayList<>(); keys.add(serverResponse.getOcs().getData().getKey()); result.setData(keys); } else { result = new RemoteOperationResult(false, getMethod); client.exhaustResponse(getMethod.getResponseBodyAsStream()); } } catch (Exception e) { result = new RemoteOperationResult(e); Log_OC.e(TAG, "Fetching of public key failed: " + result.getLogMessage(), result.getException()); } finally { if (getMethod != null) getMethod.releaseConnection(); } return result; }
From source file:com.kagilum.intellij.icescrum.IceScrumRepository.java
@Override public Task[] getIssues(@Nullable String s, int i, long l) throws Exception { String url = createCompleteUrl(); GetMethod method = new GetMethod(url); configureHttpMethod(method);/* w w w.j a v a 2 s . c o m*/ method.setRequestHeader("Content-type", "text/json"); getHttpClient().executeMethod(method); int code = method.getStatusCode(); if (code != HttpStatus.SC_OK) { checkServerStatus(code); } JsonElement json = new JsonParser().parse(method.getResponseBodyAsString()); JsonArray array = json.getAsJsonArray(); Iterator iterator = array.iterator(); List<Task> tasks = new ArrayList<Task>(); while (iterator.hasNext()) { JsonObject element = (JsonObject) iterator.next(); IceScrumTask task = new IceScrumTask(element, this.serverUrl, this.pkey); tasks.add(task); } return tasks.toArray(new Task[] {}); }
From source file:com.cubeia.backoffice.users.client.OperatorServiceClientHTTPTest.java
@Test public void testCachedConfig() throws Exception { when(client.executeMethod(any(HttpMethod.class))).thenReturn(HttpStatus.SC_OK); response = "TEST_VALUE"; String val = operatorServiceClient.getConfig(1L, OperatorConfigParamDTO.CLIENT_HELP_URL); assertEquals(response, val); operatorServiceClient.getConfig(1L, OperatorConfigParamDTO.CLIENT_HELP_URL); verify(client, times(1)).executeMethod(any(HttpMethodBase.class)); }