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:GetMethodExample.java
public static void main(String args[]) { 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 . ja va 2s . com 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.leixl.easyframework.action.httpclient.TestHttpPost.java
public static void main(String[] args) { Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("uid", 1); paramMap.put("desc", "?????"); paramMap.put("payStatus", 1); //HttpConnUtils.postHttpContent(URL, paramMap); //HttpClient/* w ww.j a va2s .c om*/ HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod(URL); // ?? NameValuePair[] data = { new NameValuePair("uid", "1"), new NameValuePair("desc", "?????"), new NameValuePair("payStatus", "1") }; // ?postMethod postMethod.setRequestBody(data); // postMethod int statusCode; try { statusCode = httpClient.executeMethod(postMethod); if (statusCode == HttpStatus.SC_OK) { StringBuffer contentBuffer = new StringBuffer(); InputStream in = postMethod.getResponseBodyAsStream(); BufferedReader reader = new BufferedReader( new InputStreamReader(in, postMethod.getResponseCharSet())); String inputLine = null; while ((inputLine = reader.readLine()) != null) { contentBuffer.append(inputLine); System.out.println("input line:" + inputLine); contentBuffer.append("/n"); } in.close(); } else if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) { // ??? Header locationHeader = postMethod.getResponseHeader("location"); String location = null; if (locationHeader != null) { location = locationHeader.getValue(); System.out.println("The page was redirected to:" + location); } else { System.err.println("Location field value is null."); } } } catch (HttpException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:UnbufferedPost.java
public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("Usage: ChunkEncodedPost <file>"); System.out.println("<file> - full path to a file to be posted"); System.exit(1);/* w ww. j av a 2 s . c o m*/ } HttpClient client = new HttpClient(); PostMethod httppost = new PostMethod("http://localhost:8080/httpclienttest/body"); File file = new File(args[0]); httppost.setRequestEntity(new InputStreamRequestEntity(new FileInputStream(file), file.length())); try { client.executeMethod(httppost); if (httppost.getStatusCode() == HttpStatus.SC_OK) { System.out.println(httppost.getResponseBodyAsString()); } else { System.out.println("Unexpected failure: " + httppost.getStatusLine().toString()); } } finally { httppost.releaseConnection(); } }
From source file:ChunkEncodedPost.java
public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("Usage: ChunkEncodedPost <file>"); System.out.println("<file> - full path to a file to be posted"); System.exit(1);/* w w w.ja v a2 s . c o m*/ } HttpClient client = new HttpClient(); PostMethod httppost = new PostMethod("http://localhost:8080/httpclienttest/body"); File file = new File(args[0]); httppost.setRequestEntity(new InputStreamRequestEntity(new FileInputStream(file))); httppost.setContentChunked(true); try { client.executeMethod(httppost); if (httppost.getStatusCode() == HttpStatus.SC_OK) { System.out.println(httppost.getResponseBodyAsString()); } else { System.out.println("Unexpected failure: " + httppost.getStatusLine().toString()); } } finally { httppost.releaseConnection(); } }
From source file:fr.cls.atoll.motu.library.misc.cas.HttpClientTutorial.java
public static void main(String[] args) { // test();/*from w w w .ja v a 2s . com*/ // System.setProperty("proxyHost", "proxy.cls.fr"); // adresse IP // System.setProperty("proxyPort", "8080"); // System.setProperty("socksProxyPort", "1080"); // // Authenticator.setDefault(new MyAuthenticator()); // Create an instance of HttpClient. // HttpClient client = new HttpClient(); HttpClient client = new HttpClient(new MultiThreadedHttpConnectionManager()); // Create a method instance. GetMethod method = new GetMethod(url); HostConfiguration hostConfiguration = new HostConfiguration(); hostConfiguration.setProxy("proxy.cls.fr", 8080); client.setHostConfiguration(hostConfiguration); // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); // String username = "xxx"; // String password = "xxx"; // Credentials credentials = new UsernamePasswordCredentials(username, password); // AuthScope authScope = new AuthScope("proxy.cls.fr", 8080); // // client.getState().setProxyCredentials(authScope, credentials); 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(); // Deal with the response. // Use caution: ensure correct character encoding and is not binary data System.out.println(new String(responseBody)); } catch (HttpException e) { System.err.println("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } finally { // Release the connection. method.releaseConnection(); } }
From source file:edu.umd.cs.submit.CommandLineSubmit.java
public static void main(String[] args) { try {/*from w w w .j av a 2 s .c om*/ Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443); File home = args.length > 0 ? new File(args[0]) : new File("."); Protocol.registerProtocol("easyhttps", easyhttps); File submitFile = new File(home, ".submit"); File submitUserFile = new File(home, ".submitUser"); File submitIgnoreFile = new File(home, ".submitIgnore"); File cvsIgnoreFile = new File(home, ".cvsignore"); if (!submitFile.canRead()) { System.out.println("Must perform submit from a directory containing a \".submit\" file"); System.out.println("No such file found at " + submitFile.getCanonicalPath()); System.exit(1); } Properties p = new Properties(); p.load(new FileInputStream(submitFile)); String submitURL = p.getProperty("submitURL"); if (submitURL == null) { System.out.println(".submit file does not contain a submitURL"); System.exit(1); } String courseName = p.getProperty("courseName"); String courseKey = p.getProperty("courseKey"); String semester = p.getProperty("semester"); String projectNumber = p.getProperty("projectNumber"); String authenticationType = p.getProperty("authentication.type"); String baseURL = p.getProperty("baseURL"); System.out.println("Submitting contents of " + home.getCanonicalPath()); System.out.println(" as project " + projectNumber + " for course " + courseName); FilesToIgnore ignorePatterns = new FilesToIgnore(); addIgnoredPatternsFromFile(cvsIgnoreFile, ignorePatterns); addIgnoredPatternsFromFile(submitIgnoreFile, ignorePatterns); FindAllFiles find = new FindAllFiles(home, ignorePatterns.getPattern()); Collection<File> files = find.getAllFiles(); boolean createdSubmitUser = false; Properties userProps = new Properties(); if (submitUserFile.canRead()) { userProps.load(new FileInputStream(submitUserFile)); } if (userProps.getProperty("cvsAccount") == null && userProps.getProperty("classAccount") == null || userProps.getProperty("oneTimePassword") == null) { System.out.println(); System.out.println( "We need to authenticate you and create a .submitUser file so you can submit your project"); createSubmitUser(submitUserFile, courseKey, projectNumber, authenticationType, baseURL); createdSubmitUser = true; userProps.load(new FileInputStream(submitUserFile)); } MultipartPostMethod filePost = createFilePost(p, find, files, userProps); HttpClient client = new HttpClient(); client.setConnectionTimeout(HTTP_TIMEOUT); int status = client.executeMethod(filePost); System.out.println(filePost.getResponseBodyAsString()); if (status == 500 && !createdSubmitUser) { System.out.println("Let's try reauthenticating you"); System.out.println(); createSubmitUser(submitUserFile, courseKey, projectNumber, authenticationType, baseURL); userProps.load(new FileInputStream(submitUserFile)); filePost = createFilePost(p, find, files, userProps); client = new HttpClient(); client.setConnectionTimeout(HTTP_TIMEOUT); status = client.executeMethod(filePost); System.out.println(filePost.getResponseBodyAsString()); } if (status != HttpStatus.SC_OK) { System.out.println("Status code: " + status); System.exit(1); } System.out.println("Submission accepted"); } catch (Exception e) { System.out.println(); System.out.println("An Error has occured during submission!"); System.out.println(); System.out.println("[DETAILS]"); System.out.println(e.getMessage()); e.printStackTrace(System.out); System.out.println(); } }
From source file:com.renlg.util.NetAssist.java
public static String delegateGet(String url) { StringBuffer response = new StringBuffer(); HttpClient client = new HttpClient(); HttpMethod method = null;/*from www .j av a 2 s .c o m*/ try { method = new GetMethod(url); client.executeMethod(method); if (method.getStatusCode() == HttpStatus.SC_OK) { BufferedReader reader = new BufferedReader( new InputStreamReader(method.getResponseBodyAsStream(), "utf8")); String line; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); } } catch (Exception e) { log.error("HTTP Get" + url + "??", e); } finally { if (method != null) method.releaseConnection(); } return response.toString(); }
From source file:com.jaspersoft.studio.server.util.HttpUtils31.java
public static HttpMethod get(HttpClient client, String url) throws HttpException, IOException { HttpMethod method = new GetMethod(url); method.setRequestHeader("Accept", "application/json"); System.out.println(method.getURI()); int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) System.err.println("Method failed: " + method.getStatusLine()); return method; }
From source file:com.kwoksys.framework.util.HttpUtils.java
/** * Gets contents from url//w w w .ja v a 2 s . c om * @param url * @return * @throws Exception */ public static String getContent(String url) throws Exception { // Create an instance of HttpClient. HttpClient client = new HttpClient(); // Create a method instance. GetMethod method = new GetMethod(url); // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); try { // Execute the method. int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { throw new Exception("HTTP method error: " + method.getStatusLine()); } // Read the response body. return new String(method.getResponseBody()); } finally { // Release the connection. method.releaseConnection(); } }
From source file:com.gargoylesoftware.htmlunit.StringWebResponse.java
/** * Helper method for constructors. Converts the specified string into {@link WebResponseData} * with other defaults specified.//from w ww . j a v a2 s . com * * @param contentString the string to be converted to a <tt>WebResponseData</tt> * @return a simple <tt>WebResponseData</tt> with defaults specified */ private static WebResponseData getWebResponseData(final String contentString, final String charset) { final byte[] content = TextUtil.stringToByteArray(contentString, charset); final List<NameValuePair> compiledHeaders = new ArrayList<NameValuePair>(); compiledHeaders.add(new NameValuePair("Content-Type", "text/html")); return new WebResponseData(content, HttpStatus.SC_OK, "OK", compiledHeaders); }