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:com.mirth.connect.client.core.ConnectServiceUtil.java
public static void registerUser(String serverId, String mirthVersion, User user, String[] protocols, String[] cipherSuites) throws ClientException { CloseableHttpClient httpClient = null; CloseableHttpResponse httpResponse = null; NameValuePair[] params = { new BasicNameValuePair("serverId", serverId), new BasicNameValuePair("version", mirthVersion), new BasicNameValuePair("user", ObjectXMLSerializer.getInstance().serialize(user)) }; HttpPost post = new HttpPost(); post.setURI(URI.create(URL_CONNECT_SERVER + URL_REGISTRATION_SERVLET)); post.setEntity(new UrlEncodedFormEntity(Arrays.asList(params), Charset.forName("UTF-8"))); RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(TIMEOUT) .setConnectionRequestTimeout(TIMEOUT).setSocketTimeout(TIMEOUT).build(); try {//w w w. java 2 s .c o m HttpClientContext postContext = HttpClientContext.create(); postContext.setRequestConfig(requestConfig); httpClient = getClient(protocols, cipherSuites); httpResponse = httpClient.execute(post, postContext); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); if ((statusCode != HttpStatus.SC_OK) && (statusCode != HttpStatus.SC_MOVED_TEMPORARILY)) { throw new Exception("Failed to connect to update server: " + statusLine); } } catch (Exception e) { throw new ClientException(e); } finally { HttpClientUtils.closeQuietly(httpResponse); HttpClientUtils.closeQuietly(httpClient); } }
From source file:com.cubeia.backoffice.users.client.OperatorServiceClientHTTPTest.java
@Test public void testNoCacheConfig() throws Exception { createServiceClient(0);/*ww w. j av a 2 s .c o m*/ 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(2)).executeMethod(any(HttpMethodBase.class)); }
From source file:com.bdaum.juploadr.uploadapi.smugrest.SmugmugMethod.java
public boolean execute() throws ProtocolException, CommunicationException { HttpMethodBase method = getMethod(); boolean rv = false; try {//from w ww .j a va 2 s.c o m int response = client.executeMethod(method); if (HttpStatus.SC_OK == response) { rv = parseResponse(method.getResponseBodyAsString()); } else { throw new CommunicationException(Messages.getString("juploadr.ui.error.bad.http.response", //$NON-NLS-1$ Activator.getStatusText(response))); } } catch (HttpException e) { throw new CommunicationException(e.getMessage(), e); } catch (IOException e) { throw new CommunicationException(e.getMessage(), e); } finally { method.releaseConnection(); } return rv; }
From source file:net.sf.sail.webapp.dao.sds.impl.HttpRestSdsUserDaoTest.java
/** * Test method for// w w w.j a v a2 s .c o m * {@link net.sf.sail.webapp.dao.sds.impl.HttpRestSdsUserDao#save(net.sf.sail.webapp.domain.sds.SdsUser)}. */ @SuppressWarnings("unchecked") public void testSave_NewUser() throws Exception { assertNull(this.sdsUser.getSdsObjectId()); this.sdsUserDao.save(this.sdsUser); assertNotNull(this.sdsUser.getSdsObjectId()); // retrieve newly created user using httpunit and compare with sdsUser // saved via DAO WebResponse webResponse = makeHttpRestGetRequest("/sail_user/" + this.sdsUser.getSdsObjectId()); assertEquals(HttpStatus.SC_OK, webResponse.getResponseCode()); Document doc = createDocumentFromResponse(webResponse); Element rootElement = doc.getRootElement(); SdsUser actualSdsUser = new SdsUser(); actualSdsUser.setFirstName(rootElement.getChild("first-name").getValue()); actualSdsUser.setLastName(rootElement.getChild("last-name").getValue()); actualSdsUser.setSdsObjectId(new Long(rootElement.getChild("id").getValue())); assertEquals(this.sdsUser, actualSdsUser); }
From source file:com.panoramagl.downloaders.PLHTTPFileDownloader.java
/**download methods*/ @Override//from w w w . j a va 2 s. c o m protected byte[] downloadFile() { this.setRunning(true); byte[] result = null; InputStream is = null; ByteArrayOutputStream bas = null; String url = this.getURL(); PLFileDownloaderListener listener = this.getListener(); boolean hasListener = (listener != null); int responseCode = -1; long startTime = System.currentTimeMillis(); // HttpClient instance HttpClient client = new HttpClient(); // Method instance HttpMethod method = new GetMethod(url); // Method parameters HttpMethodParams methodParams = method.getParams(); methodParams.setParameter(HttpMethodParams.USER_AGENT, "PanoramaGL Android"); methodParams.setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8"); methodParams.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(this.getMaxAttempts(), false)); try { // Execute the method responseCode = client.executeMethod(method); if (responseCode != HttpStatus.SC_OK) throw new IOException(method.getStatusText()); // Get content length Header header = method.getRequestHeader("Content-Length"); long contentLength = (header != null ? Long.parseLong(header.getValue()) : 1); if (this.isRunning()) { if (hasListener) listener.didBeginDownload(url, startTime); } else throw new PLRequestInvalidatedException(url); // Get response body as stream is = method.getResponseBodyAsStream(); bas = new ByteArrayOutputStream(); byte[] buffer = new byte[256]; int length = 0, total = 0; // Read stream while ((length = is.read(buffer)) != -1) { if (this.isRunning()) { bas.write(buffer, 0, length); total += length; if (hasListener) listener.didProgressDownload(url, (int) (((float) total / (float) contentLength) * 100.0f)); } else throw new PLRequestInvalidatedException(url); } if (total == 0) throw new IOException("Request data has invalid size (0)"); // Get data if (this.isRunning()) { result = bas.toByteArray(); if (hasListener) listener.didEndDownload(url, result, System.currentTimeMillis() - startTime); } else throw new PLRequestInvalidatedException(url); } catch (Throwable e) { if (this.isRunning()) { PLLog.error("PLHTTPFileDownloader::downloadFile", e); if (hasListener) listener.didErrorDownload(url, e.toString(), responseCode, result); } } finally { if (bas != null) { try { bas.close(); } catch (IOException e) { PLLog.error("PLHTTPFileDownloader::downloadFile", e); } } if (is != null) { try { is.close(); } catch (IOException e) { PLLog.error("PLHTTPFileDownloader::downloadFile", e); } } // Release the connection method.releaseConnection(); } this.setRunning(false); return result; }
From source file:com.owncloud.android.lib.resources.files.LockFileOperation.java
/** * @param client Client object//from ww w.j a v a 2 s. c om */ @Override protected RemoteOperationResult run(OwnCloudClient client) { RemoteOperationResult result; PostMethod postMethod = null; try { postMethod = new PostMethod(client.getBaseUri() + LOCK_FILE_URL + localId + JSON_FORMAT); if (!token.isEmpty()) { postMethod.setParameter(TOKEN, token); } // remote request postMethod.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE); postMethod.addRequestHeader(CONTENT_TYPE, FORM_URLENCODED); int status = client.executeMethod(postMethod, SYNC_READ_TIMEOUT, SYNC_CONNECTION_TIMEOUT); if (status == HttpStatus.SC_OK) { String response = postMethod.getResponseBodyAsString(); // Parse the response JSONObject respJSON = new JSONObject(response); String token = (String) respJSON.getJSONObject(NODE_OCS).getJSONObject(NODE_DATA).get(NODE_TOKEN); result = new RemoteOperationResult(true, postMethod); ArrayList<Object> tokenArray = new ArrayList<>(); tokenArray.add(token); result.setData(tokenArray); } else { result = new RemoteOperationResult(false, postMethod); client.exhaustResponse(postMethod.getResponseBodyAsStream()); } } catch (Exception e) { result = new RemoteOperationResult(e); Log_OC.e(TAG, "Lock file with id " + localId + " failed: " + result.getLogMessage(), result.getException()); } finally { if (postMethod != null) postMethod.releaseConnection(); } return result; }
From source file:com.braindrainpain.docker.httpsupport.HttpClientService.java
public String doGet(String url) throws IOException { URI uri = new URI(url, false); this.getMethod.setURI(uri); final int status = httpClient.executeMethod(getMethod); if (status != HttpStatus.SC_OK) { LOG.error("cannot connect to url " + url); throw new IOException("cannot connect to url " + url); }//from w w w. ja v a 2s . co m return getMethod.getResponseBodyAsString(); }
From source file:net.sourceforge.jcctray.model.HTTPCruise.java
public void forceBuild(DashBoardProject project) throws Exception { HttpMethod method = httpMethod(project); try {/*from w w w .jav a 2 s . c o m*/ if (executeMethod(method, project.getHost()) != HttpStatus.SC_OK) throw new Exception( "There was an http error connecting to the server at " + project.getHost().getHostName()); if (!isInvokeSuccessful(method, project)) throw new Exception( "The force build was not successful, the server did not return what JCCTray was expecting."); } finally { method.releaseConnection(); } }
From source file:at.ait.dme.yuma.suite.apps.map.server.tileset.TilesetGenerator.java
private String downloadImage(String dir, String url) throws TilingException { InputStream is = null;//from ww w . ja va2 s . com OutputStream os = null; try { GetMethod getImageMethod = new GetMethod(url); int statusCode = new HttpClient().executeMethod(getImageMethod); if (statusCode != HttpStatus.SC_OK) throw new TilingException("GET " + url + " returned status code:" + statusCode); is = getImageMethod.getResponseBodyAsStream(); File imageFile = new File(dir + "/" + url.substring(url.lastIndexOf("/")).replace("%", "-")); os = new FileOutputStream(imageFile); byte buf[] = new byte[1024]; int len; while ((len = is.read(buf)) > 0) os.write(buf, 0, len); return imageFile.getAbsolutePath(); } catch (Throwable t) { logger.error("failed to store image from url:" + url, t); throw new TilingException(t); } finally { try { if (os != null) os.close(); if (is != null) is.close(); } catch (IOException e) { logger.error("failed to close streams"); } } }
From source file:com.owncloud.android.lib.resources.files.ToggleFavoriteOperation.java
@Override protected RemoteOperationResult run(OwnCloudClient client) { RemoteOperationResult result = null; PropPatchMethod propPatchMethod = null; DavPropertySet newProps = new DavPropertySet(); DavPropertyNameSet removeProperties = new DavPropertyNameSet(); if (makeItFavorited) { DavProperty favoriteProperty = new DefaultDavProperty("oc:favorite", "1", Namespace.getNamespace(WebdavEntry.NAMESPACE_OC)); newProps.add(favoriteProperty);// w w w .ja va2 s.c om } else { removeProperties.add("oc:favorite", Namespace.getNamespace(WebdavEntry.NAMESPACE_OC)); } String webDavUrl = client.getNewWebdavUri().toString(); String encodedPath = Uri.encode(userID + filePath).replace("%2F", "/"); String fullFilePath = webDavUrl + "/files/" + encodedPath; try { propPatchMethod = new PropPatchMethod(fullFilePath, newProps, removeProperties); int status = client.executeMethod(propPatchMethod); boolean isSuccess = (status == HttpStatus.SC_MULTI_STATUS || status == HttpStatus.SC_OK); if (isSuccess) { result = new RemoteOperationResult(true, status, propPatchMethod.getResponseHeaders()); } else { client.exhaustResponse(propPatchMethod.getResponseBodyAsStream()); result = new RemoteOperationResult(false, status, propPatchMethod.getResponseHeaders()); } } catch (IOException e) { result = new RemoteOperationResult(e); } finally { if (propPatchMethod != null) { propPatchMethod.releaseConnection(); // let the connection available for other methods } } return result; }