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.twinsoft.convertigo.engine.PacManager.java
private String downloadPacContent(String url) throws IOException { if (url == null) { Engine.logProxyManager.debug("(PacManager) Invalid PAC script URL: null"); throw new IOException("Invalid PAC script URL: null"); }/*from ww w.j a v a2s . co m*/ HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(url); int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { throw new IOException("(PacManager) Method failed: " + method.getStatusLine()); } return IOUtils.toString(method.getResponseBodyAsStream(), "UTF-8"); }
From source file:fr.cls.atoll.motu.library.misc.cas.HttpClientTutorial.java
public static void test() { HttpClient client = new HttpClient(); client.getParams().setParameter("http.useragent", "Test Client"); client.getParams().setParameter("http.connection.timeout", new Integer(5000)); GetMethod method = new GetMethod(); FileOutputStream fos = null;//from w ww .j av a2 s. c om try { method.setURI(new URI("http://www.google.com", true)); int returnCode = client.executeMethod(method); if (returnCode != HttpStatus.SC_OK) { System.err.println("Unable to fetch default page, status code: " + returnCode); } System.err.println(method.getResponseBodyAsString()); method.setURI(new URI("http://www.google.com/images/logo.gif", true)); returnCode = client.executeMethod(method); if (returnCode != HttpStatus.SC_OK) { System.err.println("Unable to fetch image, status code: " + returnCode); } byte[] imageData = method.getResponseBody(); fos = new FileOutputStream(new File("google.gif")); fos.write(imageData); HostConfiguration hostConfig = new HostConfiguration(); hostConfig.setHost("www.yahoo.com", null, 80, Protocol.getProtocol("http")); method.setURI(new URI("/", true)); client.executeMethod(hostConfig, method); System.err.println(method.getResponseBodyAsString()); } catch (HttpException he) { System.err.println(he); } catch (IOException ie) { System.err.println(ie); } finally { method.releaseConnection(); if (fos != null) { try { fos.close(); } catch (Exception fe) { } } } }
From source file:com.sina.stock.SinaStockClient.java
/** * ???//ww w . j a v a2s. c o m * * @param stockCodes * ??"sh+?", ?"sz+?" * * @return ?List<SinaStockInfo>null * * @throws IOException * @throws HttpException * @throws ParseStockInfoException */ public List<SinaStockInfo> getStockInfo(String[] stockCodes) throws HttpException, IOException, ParseStockInfoException { String url = STOCK_URL + generateStockCodeRequest(stockCodes); HttpMethod method = new GetMethod(url); int statusCode = mHttpClient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { method.releaseConnection(); return null; } InputStream is = method.getResponseBodyAsStream(); InputStreamReader reader = new InputStreamReader(new BufferedInputStream(is), Charset.forName("gbk")); BufferedReader bReader = new BufferedReader(reader); List<SinaStockInfo> list = parseSinaStockInfosFromReader(bReader); bReader.close(); method.releaseConnection(); return list; }
From source file:fr.openwide.talendalfresco.rest.client.RestAuthenticationTest.java
public void testRestLogin() { // create client and configure it HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout); // instantiating a new method and configuring it GetMethod method = new GetMethod(restCommandUrlPrefix + "login"); method.setFollowRedirects(true); // ? // Provide custom retry handler is necessary (?) method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); NameValuePair[] params = new NameValuePair[] { new NameValuePair("username", "admin"), new NameValuePair("password", "admin") }; method.setQueryString(params);//from www . ja v a 2s . com try { // Execute the method. int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + method.getStatusLine()); } // Read the response body. byte[] responseBody = method.getResponseBody(); System.out.println(new String(responseBody)); // TODO rm HashSet<String> defaultElementSet = new HashSet<String>( Arrays.asList(new String[] { RestConstants.TAG_COMMAND, RestConstants.TAG_CODE, RestConstants.TAG_CONTENT, RestConstants.TAG_ERROR, RestConstants.TAG_MESSAGE })); HashMap<String, String> elementValueMap = new HashMap<String, String>(6); try { XMLEventReader xmlReader = XmlHelper.getXMLInputFactory() .createXMLEventReader(new ByteArrayInputStream(responseBody)); StringBuffer singleLevelTextBuf = null; while (xmlReader.hasNext()) { XMLEvent event = xmlReader.nextEvent(); switch (event.getEventType()) { case XMLEvent.CHARACTERS: case XMLEvent.CDATA: if (singleLevelTextBuf != null) { singleLevelTextBuf.append(event.asCharacters().getData()); } // else element not meaningful break; case XMLEvent.START_ELEMENT: StartElement startElement = event.asStartElement(); String elementName = startElement.getName().getLocalPart(); if (defaultElementSet.contains(elementName) // TODO another command specific level || "ticket".equals(elementName)) { // reinit buffer at start of meaningful elements singleLevelTextBuf = new StringBuffer(); } else { singleLevelTextBuf = null; // not useful } break; case XMLEvent.END_ELEMENT: if (singleLevelTextBuf == null) { break; // element not meaningful } // TODO or merely put it in the map since the element has been tested at start EndElement endElement = event.asEndElement(); elementName = endElement.getName().getLocalPart(); if (defaultElementSet.contains(elementName)) { String value = singleLevelTextBuf.toString(); elementValueMap.put(elementName, value); // TODO test if it is code and it is not OK, break to error handling } // TODO another command specific level else if ("ticket".equals(elementName)) { ticket = singleLevelTextBuf.toString(); } // singleLevelTextBuf = new StringBuffer(); // no ! in start break; } } } catch (XMLStreamException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Throwable t) { // TODO Auto-generated catch block t.printStackTrace(); //throw t; } String code = elementValueMap.get(RestConstants.TAG_CODE); assertTrue(RestConstants.CODE_OK.equals(code)); System.out.println("got ticket " + ticket); } catch (HttpException e) { // TODO e.printStackTrace(); } catch (IOException e) { // TODO e.printStackTrace(); } finally { // Release the connection. method.releaseConnection(); } }
From source file:com.mobilefirst.fiberlink.WebServiceRequest.java
/** * Description: Send Request method/*from w w w . ja v a2 s . c om*/ * @param method: the type of HTTP Method to send * @param responseToVerify: string to verify in the response * @return whether the response was verified * @throws Exception */ private boolean sendRequest(HttpMethod method, String responseToVerify) throws Exception { boolean isResponseVerified = false; try { statusCode = client.executeMethod(method); responseBody = method.getResponseBodyAsString(); System.out.println("Request URL :: " + method.getURI()); System.out.println( "------------------------------------Begin Debug: Request Headers----------------------------------------------------------\n"); Header[] requestHeaders = method.getRequestHeaders(); for (int cn = 0; cn < requestHeaders.length; cn++) { System.out.println(requestHeaders[cn].toString()); } System.out.println( "------------------------------------Begin Debug: Response Headers----------------------------------------------------------\n"); Header[] responseHeaders = method.getResponseHeaders(); for (int cn = 0; cn < responseHeaders.length; cn++) { System.out.println(responseHeaders[cn].toString()); } System.out.println( "------------------------------------End Debug----------------------------------------------------------\n"); if (statusCode != HttpStatus.SC_OK) { throw new Exception("POST method failed :: " + statusCode + " and ResponseBody :: " + responseBody); } else { System.out.println( "------------------------------------Response Start----------------------------------------------------------\n"); System.out.println(responseBody + "\n"); System.out.println( "------------------------------------Resoonse End----------------------------------------------------------"); if (null == jsessionId) { for (int cnt = 0; cnt < responseHeaders.length; cnt++) { // System.out.println(headers[cnt].toString()); if (responseHeaders[cnt].toString().contains("Set-Cookie: JSESSIONID=")) { jsessionId = getPatternMatches("JSESSIONID=(.+); Path", responseHeaders[cnt].toString(), false); System.out.println("JESSIONID: " + jsessionId); break; } } } if (responseBody.toLowerCase().contains(responseToVerify.toLowerCase())) { System.out.println("RESPONSE VERIFIED. Contains: " + responseToVerify); isResponseVerified = true; } } } catch (Exception e) { e.printStackTrace(); throw new Exception("Exception in sendRequest method..." + e.getMessage()); } return isResponseVerified; }
From source file:com.thoughtworks.twist.mingle.core.MingleClient.java
public boolean validate() { HttpMethod method = getMethod(loginUrl()); try {/* www . j a v a 2 s . c o m*/ int httpStatus = executeMethod(method); switch (httpStatus) { case HttpStatus.SC_OK: return true; case HttpStatus.SC_UNAUTHORIZED: throw new MingleAuthenticationException(); } } finally { if (method != null) method.releaseConnection(); } return false; }
From source file:eu.alefzero.owncloud.authenticator.ConnectionCheckerRunnable.java
private boolean tryConnection(Uri uri) { WebdavClient wc = new WebdavClient(); wc.allowSelfsignedCertificates();/*from w w w. j a va 2 s . com*/ GetMethod get = new GetMethod(uri.toString()); boolean retval = false; try { int status = wc.executeMethod(get, TRY_CONNECTION_TIMEOUT); switch (status) { case HttpStatus.SC_OK: { String response = get.getResponseBodyAsString(); JSONObject json = new JSONObject(response); if (!json.getBoolean("installed")) { mLatestResult = ResultType.INSTANCE_NOT_CONFIGURED; break; } mOCVersion = new OwnCloudVersion(json.getString("version")); if (!mOCVersion.isVersionValid()) break; retval = true; break; } case HttpStatus.SC_NOT_FOUND: mLatestResult = ResultType.FILE_NOT_FOUND; break; case HttpStatus.SC_INTERNAL_SERVER_ERROR: mLatestResult = ResultType.INSTANCE_NOT_CONFIGURED; break; default: mLatestResult = ResultType.UNKNOWN_ERROR; Log.e(TAG, "Not handled status received from server: " + status); } } catch (Exception e) { if (e instanceof UnknownHostException || e instanceof ConnectException || e instanceof SocketTimeoutException) { mLatestResult = ResultType.HOST_NOT_AVAILABLE; } else if (e instanceof JSONException) { mLatestResult = ResultType.INSTANCE_NOT_CONFIGURED; } else if (e instanceof SSLHandshakeException) { mLatestResult = ResultType.SSL_INIT_ERROR; } else { mLatestResult = ResultType.UNKNOWN_ERROR; } e.printStackTrace(); } return retval; }
From source file:com.dlecan.agreg.AgregResultsBot.java
public boolean isResultatsDisponibles(String type) throws Exception { boolean resultatsDisponibles = false; String urlAppelee = URL_PUBLINET_PREFIX + type + URL_PUBLINET_SUFFIX; HttpMethod getUrlPublinet = new GetMethod(urlAppelee); try {/* w w w. j a v a 2s . c om*/ int status = client.executeMethod(getUrlPublinet); if (status == HttpStatus.SC_OK) { InputStream streamPage = getUrlPublinet.getResponseBodyAsStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(streamPage)); String line; while ((line = reader.readLine()) != null) { if (line.toUpperCase().contains("AUCUN CANDIDAT ADMIS")) { resultatsDisponibles = false; break; } else if (line.toUpperCase() .contains("Cliquez sur une des lettres de l'alphabet".toUpperCase())) { resultatsDisponibles = true; break; } else { // Le systme dconne } } if (resultatsDisponibles) { while ((line = reader.readLine()) != null) { if (line.toUpperCase().contains("VALADE")) { recue = true; messageAEnvoyer = urlAppelee + "\n\n" + line; break; } else { // Le systme dconne } } } } else { logger.error("Method failed: {}", getUrlPublinet.getStatusLine()); } } finally { getUrlPublinet.releaseConnection(); } return resultatsDisponibles; }
From source file:com.owncloud.activity.Downloader.java
public void downloadFile(Intent i) { if (isOnline()) { String url = i.getData().toString(); GetMethod gm = new GetMethod(url); try {/*w w w . j a v a 2 s.c o m*/ int status = BaseActivity.httpClient.executeMethod(gm); // Toast.makeText(getApplicationContext(), String.valueOf(status),2).show(); Log.e("HttpStatus", "==============>" + String.valueOf(status)); if (status == HttpStatus.SC_OK) { InputStream input = gm.getResponseBodyAsStream(); String fileName = new StringBuffer(url).reverse().toString(); String[] fileNameArray = fileName.split("/"); fileName = new StringBuffer(fileNameArray[0]).reverse().toString(); fileName = URLDecoder.decode(fileName); File folder = new File(BaseActivity.mDownloadDest); boolean success = false; if (!folder.exists()) { success = folder.mkdir(); } if (!success) { // Do something on success File file = new File(BaseActivity.mDownloadDest, fileName); OutputStream fOut = new FileOutputStream(file); int byteCount = 0; byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = input.read(buffer)) != -1) { fOut.write(buffer, 0, bytesRead); byteCount += bytesRead; // DashBoardActivity.updateNotation(); } fOut.flush(); fOut.close(); } else { // Do something else on failure Log.d("Download Prob..", String.valueOf(success) + ", Some problem in folder creating"); } } } catch (HttpException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } gm.releaseConnection(); Bundle extras = i.getExtras(); if (extras != null) { Messenger messenger = (Messenger) extras.get(EXTRA_MESSENGER); Message msg = Message.obtain(); msg.arg1 = Activity.RESULT_OK; try { messenger.send(msg); } catch (android.os.RemoteException e1) { Log.w(getClass().getName(), "Exception sending message", e1); } } } else { WebNetworkAlert(); } }
From source file:com.cloud.cluster.ClusterServiceServletImpl.java
private String executePostMethod(HttpClient client, PostMethod method) { int response = 0; String result = null;/*from w ww .j av a2s. c o m*/ try { long startTick = System.currentTimeMillis(); response = client.executeMethod(method); if (response == HttpStatus.SC_OK) { result = method.getResponseBodyAsString(); if (s_logger.isDebugEnabled()) { s_logger.debug("POST " + _serviceUrl + " response :" + result + ", responding time: " + (System.currentTimeMillis() - startTick) + " ms"); } } else { s_logger.error("Invalid response code : " + response + ", from : " + _serviceUrl + ", method : " + method.getParameter("method") + " responding time: " + (System.currentTimeMillis() - startTick)); } } catch (HttpException e) { s_logger.error("HttpException from : " + _serviceUrl + ", method : " + method.getParameter("method")); } catch (IOException e) { s_logger.error("IOException from : " + _serviceUrl + ", method : " + method.getParameter("method")); } catch (Throwable e) { s_logger.error("Exception from : " + _serviceUrl + ", method : " + method.getParameter("method") + ", exception :", e); } finally { method.releaseConnection(); } return result; }