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.sdm.core.resource.RestResource.java
@Override public IBaseResponse getAll() { DefaultResponse response = this.validateCache(); // Cache validation if (response != null) { return response; }/*from w w w. j av a 2 s . c o m*/ try { List<T> data = (List<T>) getDAO().fetchAll(); ListModel<T> content = new ListModel<T>(data); response = new DefaultResponse<>(HttpStatus.SC_OK, ResponseType.SUCCESS, content); response.setHeaders(this.buildCache()); return response; } catch (Exception e) { getLogger().error(e); throw e; } }
From source file:com.cloud.utils.net.HTTPUtils.java
/** * @param responseCode//from ww w . j a va2s . co m * @return */ public static boolean verifyResponseCode(int responseCode) { switch (responseCode) { case HttpStatus.SC_OK: case HttpStatus.SC_MOVED_PERMANENTLY: case HttpStatus.SC_MOVED_TEMPORARILY: return true; default: return false; } }
From source file:edu.tsinghua.lumaqq.test.CustomHeadUploader.java
/** * /* w w w .j a v a 2 s . c om*/ * * @param filename */ public void upload(String filename, QQUser user) { HttpClient client = new HttpClient(); HostConfiguration conf = new HostConfiguration(); conf.setHost(QQ.QQ_SERVER_UPLOAD_CUSTOM_HEAD); client.setHostConfiguration(conf); PostMethod method = new PostMethod("/cgi-bin/cface/upload"); method.addRequestHeader("Accept", "*/*"); method.addRequestHeader("Pragma", "no-cache"); StringPart uid = new StringPart("clientuin", String.valueOf(user.getQQ())); uid.setContentType(null); uid.setTransferEncoding(null); //StringPart clientkey = new StringPart("clientkey", "0D649E66B0C1DBBDB522CE9C846754EF6AFA10BBF1A48A532DF6369BBCEF6EE7"); //StringPart clientkey = new StringPart("clientkey", "3285284145CC19EC0FFB3B25E4F6817FF3818B0E72F1C4E017D9238053BA2040"); StringPart clientkey = new StringPart("clientkey", "2FEEBE858DAEDFE6352870E32E5297ABBFC8C87125F198A5232FA7ADA9EADE67"); //StringPart clientkey = new StringPart("clientkey", "8FD643A7913C785AB612F126C6CD68A253F459B90EBCFD9375053C159418AF16"); // StringPart clientkey = new StringPart("clientkey", Util.convertByteToHexStringWithoutSpace(user.getClientKey())); clientkey.setContentType(null); clientkey.setTransferEncoding(null); //StringPart sign = new StringPart("sign", "2D139466226299A73F8BCDA7EE9AB157E8D9DA0BB38B6F4942A1658A00BD4C1FEE415838810E5AEF40B90E2AA384A875"); //StringPart sign = new StringPart("sign", "50F479417088F26EFC75B9BCCF945F35346188BB9ADD3BDF82098C9881DA086E3B28D56726D6CB2331909B62459E1E62"); //StringPart sign = new StringPart("sign", "31A69198C19A7C4BFB60DCE352FE2CC92C9D27E7C7FEADE1CBAAFD988906981ECC0DD1782CBAE88A2B716F84F9E285AA"); StringPart sign = new StringPart("sign", "68FFB636DE63D164D4072D7581213C77EC7B425DDFEB155428768E1E409935AA688AC88910A74C5D2D94D5EF2A3D1764"); sign.setContentType(null); sign.setTransferEncoding(null); FilePart file; try { file = new FilePart("customfacefile", filename, new File(filename)); } catch (FileNotFoundException e) { return; } Part[] parts = new Part[] { uid, clientkey, sign, file }; MultipartRequestEntity entity = new MultipartRequestEntity(parts, method.getParams()); method.setRequestEntity(entity); try { client.executeMethod(method); if (method.getStatusCode() == HttpStatus.SC_OK) { Header header = method.getResponseHeader("CFace-Msg"); System.out.println(header.getValue()); header = method.getResponseHeader("CFace-RetCode"); System.out.println(header.getValue()); } } catch (HttpException e) { return; } catch (IOException e) { return; } finally { method.releaseConnection(); } }
From source file:com.intuit.wasabi.api.EventsResourceTest.java
@Test public void getEventsQueueLength() throws Exception { assertThat(resource.getEventsQueueLength().getStatus(), is(HttpStatus.SC_OK)); }
From source file:net.paissad.waqtsalat.utils.DownloadHelper.java
/** * <p>//from ww w. j a v a2s . c o m * Download a resource from the specified url and save it to the specified * file. * </p> * <b>Note</b>: If you plan to cancel the download at any time, then this * method should be embed into it's own thread. * <p> * <b>Example</b>: * * <pre> * final DownloadHelper downloader = new DownloadHelper(); * Thread t = new Thread() { * public void run() { * try { * downloader.download("http://domain.com/file.zip", new File("/tmp/output.zip")); * } catch (Exception e) { * ... * } * } * }; * t.start(); * // Waits 3 seconds and then cancels the download. * Thread.sleep(3 * 1000L); * downloader.cancel(); * ... * </pre> * * </p> * * @param url * - The url of the file to download. * @param file * - The downloaded file (where it will be stored). * @throws IOException * @throws HttpException */ public void download(final String url, final File file) throws HttpException, IOException { GetMethod method = null; InputStream responseBody = null; OutputStream out = null; try { final boolean fileExisted = file.exists(); HttpClient client = new HttpClient(); method = new GetMethod(url); method.setFollowRedirects(true); method.setRequestHeader("User-Agent", WSConstants.WS_USER_AGENT); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); method.getParams().setParameter(HttpMethodParams.WARN_EXTRA_INPUT, Boolean.TRUE); // Execute the method. int responseCode = client.executeMethod(method); if (responseCode != HttpStatus.SC_OK) { logger.error("Http method failed : {}.", method.getStatusLine().toString()); } // Read the response body. responseBody = method.getResponseBodyAsStream(); // Let's try to compute the amount of total bytes of the file to // download. URL u = new URL(url); URLConnection urlc = u.openConnection(); this.totalBytes = urlc.getContentLength(); long lastModified = urlc.getLastModified(); // The OutputStream for the 'downloaded' file. out = new BufferedOutputStream(new FileOutputStream(file)); this.updateState(DownloadState.IN_PROGRESS); byte[] data = new byte[BUFFER_SIZE]; int length; while ((length = responseBody.read(data, 0, BUFFER_SIZE)) != -1 && !isCancelled) { out.write(data, 0, length); this.bytesDownloaded += length; setChanged(); notifyObservers(getBytesDownloaded()); } if (isCancelled) { this.updateState(DownloadState.CANCELED); logger.info("The download has been cancelled."); } else { // The download was not cancelled. out.flush(); if (lastModified > 0) { file.setLastModified(lastModified); } if (bytesDownloaded != totalBytes) { logger.warn("The expected bytes to download is {}, but got {}.", getTotalBytes(), getBytesDownloaded()); this.updateState(DownloadState.ERROR); } this.updateState(DownloadState.FINISHED); logger.info("Download of '{}' finished successfully.", url); } // If the file did not exist before the download but does exit now, // we must remove it if an error occurred or if the download was // cancelled. if (getState() == DownloadState.CANCELED || getState() == DownloadState.ERROR) { if (!fileExisted && file.exists()) { FileUtils.forceDelete(file); } } } catch (HttpException he) { this.updateState(DownloadState.ERROR); logger.error("Fatal protocol violation : " + he); throw new HttpException("Error while downloading from the url '" + url + "'", he); } catch (IOException ioe) { this.updateState(DownloadState.ERROR); logger.error("Fatal transport error : " + ioe); throw new IOException(ioe); } finally { if (method != null) method.releaseConnection(); if (responseBody != null) responseBody.close(); if (out != null) out.close(); } }
From source file:com.gargoylesoftware.htmlunit.WebResponseImplTest.java
/** * @throws Exception if the test fails/*from w w w .ja v a2 s . c o m*/ */ @Test public void quotedCharset() throws Exception { final String xml = "<books id='myId'>\n" + " <book>\n" + " <title>Immortality</title>\n" + " <author>John Smith</author>\n" + " </book>\n" + "</books>"; final List<String> collectedAlerts = new ArrayList<String>(); final WebClient client = new WebClient(); client.setAlertHandler(new CollectingAlertHandler(collectedAlerts)); final MockWebConnection conn = new MockWebConnection(); final List<? extends NameValuePair> emptyList = Collections.emptyList(); conn.setResponse(URL_FIRST, xml, HttpStatus.SC_OK, "OK", "text/xml; charset=\"ISO-8859-1\"", emptyList); client.setWebConnection(conn); client.getPage(URL_FIRST); }
From source file:com.kagilum.plugins.icescrum.IceScrumSession.java
private boolean executeMethod(PostMethod method, int expectedCode) { boolean result = false; try {//w w w. j av a 2 s. co m setAuthentication(); client.executeMethod(method); int code = method.getStatusCode(); if (code != HttpStatus.SC_OK && (expectedCode != 0 && expectedCode != code)) { checkServerStatus(code); } else { body = IOUtils.toString(method.getResponseBodyAsStream()); result = true; } } catch (IOException e) { httpError = e.getMessage(); LOGGER.log(Level.WARNING, httpError, e); } finally { method.releaseConnection(); } return result; }
From source file:com.zb.app.biz.service.WeixinTest.java
public boolean sendMessage(String fakeid, String content) { if (isLogin) { PostMethod post = new PostMethod(sendUrl); post.setRequestHeader("Cookie", this.cookiestr); post.setRequestHeader("Host", "mp.weixin.qq.com"); post.setRequestHeader("Referer", "https://mp.weixin.qq.com/cgi-bin/singlesendpage?t=message/send&action=index&token=" + token + "&tofakeid=" + fakeid + "&lang=zh_CN"); post.setRequestHeader("Content-Type", "text/html;charset=UTF-8"); post.addParameter(new NameValuePair("type", "1")); post.addParameter(new NameValuePair("content", content)); post.addParameter(new NameValuePair("error", "false")); post.addParameter(new NameValuePair("imgcode", "")); post.addParameter(new NameValuePair("tofakeid", "681435581")); post.addParameter(new NameValuePair("token", token)); post.addParameter(new NameValuePair("ajax", "1")); try {// www.j a va 2s . co m int code = httpClient.executeMethod(post); if (HttpStatus.SC_OK == code) { System.out.println(post.getResponseBodyAsString()); } } catch (Exception e) { e.printStackTrace(); } } else { login(); sendMessage(fakeid, content); } return false; }
From source file:com.unicauca.braim.http.HttpBraimClient.java
public User GET_User(String username, String access_token) throws IOException, Exception { User user = null;/*w ww.ja v a2 s. co m*/ Gson gson = new Gson(); String token_data = "?braim_token=" + access_token; GetMethod method = new GetMethod(api_url + "/api/v1/users/" + username + token_data); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + method.getStatusLine()); throw new Exception("The username or password are invalid"); } byte[] responseBody = method.getResponseBody(); String response = new String(responseBody, "UTF-8"); user = gson.fromJson(response, User.class); System.out.println(user.getEmail() + "Has been retrieved"); return user; }
From source file:com.twinsoft.convertigo.engine.admin.services.mobiles.GetPackage.java
@Override protected void writeResponseResult(HttpServletRequest request, HttpServletResponse response) throws Exception { String project = Keys.project.value(request); MobileApplication mobileApplication = GetBuildStatus.getMobileApplication(project); if (mobileApplication == null) { throw new ServiceException("no such mobile application"); } else {//from w w w . ja v a 2s .com boolean bAdminRole = Engine.authenticatedSessionManager.hasRole(request.getSession(), Role.WEB_ADMIN); if (!bAdminRole && mobileApplication.getAccessibility() == Accessibility.Private) { throw new AuthenticationException("Authentication failure: user has not sufficient rights!"); } } String platformName = Keys.platform.value(request); String finalApplicationName = mobileApplication.getComputedApplicationName(); String mobileBuilderPlatformURL = EnginePropertiesManager .getProperty(PropertyName.MOBILE_BUILDER_PLATFORM_URL); PostMethod method; int methodStatusCode; InputStream methodBodyContentInputStream; URL url = new URL(mobileBuilderPlatformURL + "/getpackage"); HostConfiguration hostConfiguration = new HostConfiguration(); hostConfiguration.setHost(new URI(url.toString(), true)); HttpState httpState = new HttpState(); Engine.theApp.proxyManager.setProxy(hostConfiguration, httpState, url); method = new PostMethod(url.toString()); try { HeaderName.ContentType.setRequestHeader(method, MimeType.WwwForm.value()); method.setRequestBody(new NameValuePair[] { new NameValuePair("application", finalApplicationName), new NameValuePair("platformName", platformName), new NameValuePair("auth_token", mobileApplication.getComputedAuthenticationToken()), new NameValuePair("endpoint", mobileApplication.getComputedEndpoint(request)) }); methodStatusCode = Engine.theApp.httpClient.executeMethod(hostConfiguration, method, httpState); methodBodyContentInputStream = method.getResponseBodyAsStream(); if (methodStatusCode != HttpStatus.SC_OK) { byte[] httpBytes = IOUtils.toByteArray(methodBodyContentInputStream); String sResult = new String(httpBytes, "UTF-8"); throw new ServiceException("Unable to get package for project '" + project + "' (final app name: '" + finalApplicationName + "').\n" + sResult); } try { String contentDisposition = method.getResponseHeader(HeaderName.ContentDisposition.value()) .getValue(); HeaderName.ContentDisposition.setHeader(response, contentDisposition); } catch (Exception e) { HeaderName.ContentDisposition.setHeader(response, "attachment; filename=\"" + project + "\""); } try { response.setContentType(method.getResponseHeader(HeaderName.ContentType.value()).getValue()); } catch (Exception e) { response.setContentType(MimeType.OctetStream.value()); } OutputStream responseOutputStream = response.getOutputStream(); IOUtils.copy(methodBodyContentInputStream, responseOutputStream); } catch (IOException ioex) { // Fix for ticket #4698 if (!ioex.getClass().getSimpleName().equalsIgnoreCase("ClientAbortException")) { // fix for #5042 throw ioex; } } finally { method.releaseConnection(); } }