List of usage examples for org.apache.commons.httpclient HttpStatus getStatusText
public static String getStatusText(int statusCode)
From source file:com.gisgraphy.rest.RestClient.java
private int executeAndCheckStatusCode(HttpMethod httpMethod) throws IOException, HttpException, RestClientException { int statusCode = httpClient.executeMethod(httpMethod); if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED && statusCode != HttpStatus.SC_NO_CONTENT) { throw new RestClientException(statusCode, "restclient exception for " + httpMethod.getURI() + " : " + statusCode + ", " + HttpStatus.getStatusText(statusCode)); }/*from w w w . jav a 2s . c o m*/ return statusCode; }
From source file:fedora.client.FedoraClient.java
/** * Upload the given file to Fedora's upload interface via HTTP POST. * * @return the temporary id which can then be passed to API-M requests as a * URL. It will look like uploaded://123 *//* ww w.j av a 2 s. co m*/ public String uploadFile(File file) throws IOException { PostMethod post = null; try { // prepare the post method post = new PostMethod(getUploadURL()); post.setDoAuthentication(true); post.getParams().setParameter("Connection", "Keep-Alive"); // chunked encoding is not required by the Fedora server, // but makes uploading very large files possible post.setContentChunked(true); // add the file part Part[] parts = { new FilePart("file", file) }; post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); // execute and get the response int responseCode = getHttpClient().executeMethod(post); String body = null; try { body = post.getResponseBodyAsString(); } catch (Exception e) { LOG.warn("Error reading response body", e); } if (body == null) { body = "[empty response body]"; } body = body.trim(); if (responseCode != HttpStatus.SC_CREATED) { throw new IOException("Upload failed: " + HttpStatus.getStatusText(responseCode) + ": " + replaceNewlines(body, " ")); } else { return replaceNewlines(body, ""); } } finally { if (post != null) { post.releaseConnection(); } } }
From source file:com.benfante.jslideshare.SlideShareConnectorImpl.java
public InputStream sendMultiPartMessage(String url, Map<String, String> parameters, Map<String, File> files) throws IOException, SlideShareErrorException { HttpClient client = createHttpClient(); PostMethod method = new PostMethod(url); List<Part> partList = new ArrayList(); partList.add(createStringPart("api_key", this.apiKey)); Date now = new Date(); String ts = Long.toString(now.getTime() / 1000); String hash = DigestUtils.shaHex(this.sharedSecret + ts).toLowerCase(); partList.add(createStringPart("ts", ts)); partList.add(createStringPart("hash", hash)); Iterator<Map.Entry<String, String>> entryIt = parameters.entrySet().iterator(); while (entryIt.hasNext()) { Map.Entry<String, String> entry = entryIt.next(); partList.add(createStringPart(entry.getKey(), entry.getValue())); }//www.ja v a 2 s. c om Iterator<Map.Entry<String, File>> entryFileIt = files.entrySet().iterator(); while (entryFileIt.hasNext()) { Map.Entry<String, File> entry = entryFileIt.next(); partList.add(createFilePart(entry.getKey(), entry.getValue())); } MultipartRequestEntity requestEntity = new MultipartRequestEntity( partList.toArray(new Part[partList.size()]), method.getParams()); method.setRequestEntity(requestEntity); logger.debug("Sending multipart POST message to " + method.getURI().getURI() + " with parts " + partList); int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { logger.debug("Server replied with a " + statusCode + " HTTP status code (" + HttpStatus.getStatusText(statusCode) + ")"); throw new SlideShareErrorException(statusCode, HttpStatus.getStatusText(statusCode)); } if (logger.isDebugEnabled()) { logger.debug(method.getResponseBodyAsString()); } InputStream result = new ByteArrayInputStream(method.getResponseBody()); method.releaseConnection(); return result; }
From source file:com.github.maven.plugin.client.impl.GithubClientImpl.java
public void upload(String artifactName, File file, String description, String repositoryUrl) { assertNotNull(artifactName, "artifactName"); assertNotNull(file, "file"); assertNotNull(repositoryUrl, "repositoryUrl"); assertStartsWith(repositoryUrl, GITHUB_REPOSITORY_URL_PREFIX, "repositoryUrl"); PostMethod githubPost = new PostMethod(toRepositoryDownloadUrl(repositoryUrl)); githubPost.setRequestBody(new NameValuePair[] { new NameValuePair("login", login), new NameValuePair("token", token), new NameValuePair("file_name", artifactName), new NameValuePair("file_size", String.valueOf(file.length())), new NameValuePair("description", description == null ? "" : description) }); try {//from ww w . j a va 2s.c o m int response = httpClient.executeMethod(githubPost); if (response == HttpStatus.SC_OK) { ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readValue(githubPost.getResponseBodyAsString(), JsonNode.class); PostMethod s3Post = new PostMethod(GITHUB_S3_URL); Part[] parts = { new StringPart("Filename", artifactName), new StringPart("policy", node.path("policy").getTextValue()), new StringPart("success_action_status", "201"), new StringPart("key", node.path("path").getTextValue()), new StringPart("AWSAccessKeyId", node.path("accesskeyid").getTextValue()), new StringPart("Content-Type", node.path("mime_type").getTextValue()), new StringPart("signature", node.path("signature").getTextValue()), new StringPart("acl", node.path("acl").getTextValue()), new FilePart("file", file) }; MultipartRequestEntity partEntity = new MultipartRequestEntity(parts, s3Post.getParams()); s3Post.setRequestEntity(partEntity); int s3Response = httpClient.executeMethod(s3Post); if (s3Response != HttpStatus.SC_CREATED) { throw new GithubException( "Cannot upload " + file.getName() + " to repository " + repositoryUrl); } s3Post.releaseConnection(); } else if (response == HttpStatus.SC_NOT_FOUND) { throw new GithubRepositoryNotFoundException("Cannot found repository " + repositoryUrl); } else if (response == HttpStatus.SC_UNPROCESSABLE_ENTITY) { throw new GithubArtifactAlreadyExistException( "File " + artifactName + " already exist in " + repositoryUrl + " repository"); } else { throw new GithubException("Error " + HttpStatus.getStatusText(response)); } } catch (IOException e) { throw new GithubException(e); } githubPost.releaseConnection(); }
From source file:fr.eurecom.nerd.core.proxy.ExtractivClient.java
/** * Get the output from the REST server/*from www . jav a 2 s . c o m*/ */ private static InputStream fetchHttpRequest(final HttpMethodBase method) throws BadInputException { try { final int statusCode = getClient().executeMethod(method); if (statusCode != HttpStatus.SC_OK) { throw new BadInputException( "webpage status " + HttpStatus.getStatusText(statusCode) + "(" + statusCode + ")"); } final InputStream is = new ByteArrayInputStream(method.getResponseBody()); final GZIPInputStream zippedInputStream = new GZIPInputStream(is); return zippedInputStream; } catch (HttpException e) { throw new BadInputException("Fatal protocol violation " + e.getMessage(), e); } catch (IOException e) { //e.g. www.google.assadsaddsa throw new BadInputException("Fatal transport error " + e.getMessage(), e); } finally { method.releaseConnection(); } }
From source file:com._17od.upm.transport.HTTPTransport.java
public byte[] get(String url, String username, String password) throws TransportException { byte[] retVal = null; GetMethod method = new GetMethod(url); //This part is wrapped in a try/finally so that we can ensure //the connection to the HTTP server is always closed cleanly try {/*from w w w. ja va 2 s . c o m*/ //Set the authentication details if (username != null) { Credentials creds = new UsernamePasswordCredentials(new String(username), new String(password)); URL urlObj = new URL(url); AuthScope authScope = new AuthScope(urlObj.getHost(), urlObj.getPort()); client.getState().setCredentials(authScope, creds); client.getParams().setAuthenticationPreemptive(true); } int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { throw new TransportException("There's been some kind of problem getting the URL [" + url + "].\n\nThe HTTP error message is [" + HttpStatus.getStatusText(statusCode) + "]"); } retVal = method.getResponseBody(); } catch (MalformedURLException e) { throw new TransportException(e); } catch (HttpException e) { throw new TransportException(e); } catch (IOException e) { throw new TransportException(e); } finally { method.releaseConnection(); } return retVal; }
From source file:com.apatar.ui.JFeatureRequestHelpDialog.java
private void addListeners() { sendButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { PostMethod filePost = new PostMethod(getUrl()); // filePost.getParameters().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true); try { if (!CoreUtils.validEmail(emailField.getText())) { JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME, "E-mail address is invalid! Please, write a valid e-mail."); return; }/*from w w w.j av a 2s. c om*/ Part[] parts; parts = new Part[4]; parts[0] = new StringPart("FeatureRequest", text.getText()); parts[1] = new StringPart("FirstName", firstNameField.getText()); parts[2] = new StringPart("LastName", lastNameField.getText()); parts[3] = new StringPart("Email", emailField.getText()); filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); int status = client.executeMethod(filePost); if (status != HttpStatus.SC_OK) JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME, "Upload failed, response=" + HttpStatus.getStatusText(status)); else { JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME, "Your message has been sent. Thank you!"); dispose(); } } catch (Exception ex) { ex.printStackTrace(); } finally { filePost.releaseConnection(); } } }); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { dispose(); } }); }
From source file:com.apatar.ui.JSubmitHelpDialog.java
private void addListeners() { sendButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { PostMethod filePost = new PostMethod(getUrl()); try { if (!CoreUtils.validEmail(emailField.getText())) { JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME, "E-mail address is invalid! Please, write a valid e-mail."); return; }/*www . ja v a2 s . c o m*/ List<File> targetFiles = getAttachFile(); List<FilePart> fParts = new ArrayList<FilePart>(); int i = 1; for (File file : targetFiles) { try { fParts.add(new FilePart("file" + i, file)); i++; } catch (java.io.FileNotFoundException ef) { } } int size = fParts.size() + 4; Part[] parts = new Part[size]; parts[0] = new StringPart("BugInformation", text.getText()); parts[1] = new StringPart("FirstName", firstNameField.getText()); parts[2] = new StringPart("LastName", lastNameField.getText()); parts[3] = new StringPart("Email", emailField.getText()); i = 4; for (FilePart fp : fParts) parts[i++] = fp; filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); int status = client.executeMethod(filePost); if (status != HttpStatus.SC_OK) JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME, "Upload failed, response=" + HttpStatus.getStatusText(status)); else { JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME, "Your message has been sent. Thank you!"); dispose(); } } catch (Exception ex) { ex.printStackTrace(); } finally { filePost.releaseConnection(); } } }); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { dispose(); } }); }
From source file:com.globalsight.everest.webapp.applet.admin.customer.FileSystemApplet.java
/** * Zip the selected files and send the zip to the server. * @param p_filesToBeZipped - A list of selected files to be uploaded. * @param p_targetURL - The target URL representing server URL. * @param p_targetLocation - A string representing the link to the next page. */// w ww .j a v a 2s .co m public void sendZipFile(File[] p_filesToBeZipped, String p_targetURL, final String p_targetLocation) throws Exception { StringBuffer sb = new StringBuffer(); sb.append("GS_"); sb.append(System.currentTimeMillis()); sb.append(".zip"); File targetFile = getFile(sb.toString()); ZipIt.addEntriesToZipFile(targetFile, p_filesToBeZipped); m_progressBar.setValue(30); PostMethod filePost = new PostMethod(p_targetURL + "&doPost=true"); filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true); filePost.setDoAuthentication(true); try { Part[] parts = { new FilePart(targetFile.getName(), targetFile) }; m_progressBar.setValue(40); filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); HttpClient client = new HttpClient(); setUpClientForProxy(client); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); m_progressBar.setValue(50); int status = client.executeMethod(filePost); if (status == HttpStatus.SC_OK) { //no need to ask for auth again since the first upload was fine s_authPrompter.setAskForAuthentication(false); m_progressBar.setValue(60); InputStream is = filePost.getResponseBodyAsStream(); m_progressBar.setValue(70); ObjectInputStream inputStreamFromServlet = new ObjectInputStream(is); Vector incomingData = (Vector) inputStreamFromServlet.readObject(); inputStreamFromServlet.close(); if (incomingData != null) { if (incomingData.elementAt(0) instanceof ExceptionMessage) { resetProgressBar(); AppletHelper.displayErrorPage((ExceptionMessage) incomingData.elementAt(0), this); } } else { boolean deleted = targetFile.delete(); m_progressBar.setValue(100); try { Thread.sleep(1000); } catch (Exception e) { } // now move to some other page... goToTargetPage(p_targetLocation); } } else { //authentication may have failed, reset the need to ask s_authPrompter.setAskForAuthentication(true); resetProgressBar(); String errorMessage = "Upload failed because: (" + status + ") " + HttpStatus.getStatusText(status); if (status == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) { errorMessage = "Incorrect NTDomain\\username or password entered. Hit 'upload' again to re-try."; } AppletHelper.getErrorDlg(errorMessage, null); } } catch (Exception ex) { //authentication may have failed, reset the need to ask s_authPrompter.setAskForAuthentication(true); resetProgressBar(); System.err.println(ex); AppletHelper.getErrorDlg(ex.getMessage(), null); } finally { filePost.releaseConnection(); } }
From source file:com.benfante.jslideshare.SlideShareConnectorImpl.java
public InputStream sendGetMessage(String url, Map<String, String> parameters) throws IOException, SlideShareErrorException { HttpClient client = createHttpClient(); GetMethod method = new GetMethod(url); NameValuePair[] params = new NameValuePair[parameters.size() + 3]; int i = 0;//w ww . j av a2s .c om params[i++] = new NameValuePair("api_key", this.apiKey); Iterator<Map.Entry<String, String>> entryIt = parameters.entrySet().iterator(); while (entryIt.hasNext()) { Map.Entry<String, String> entry = entryIt.next(); params[i++] = new NameValuePair(entry.getKey(), entry.getValue()); } Date now = new Date(); String ts = Long.toString(now.getTime() / 1000); String hash = DigestUtils.shaHex(this.sharedSecret + ts).toLowerCase(); params[i++] = new NameValuePair("ts", ts); params[i++] = new NameValuePair("hash", hash); method.setQueryString(params); logger.debug("Sending GET message to " + method.getURI().getURI() + " with parameters " + Arrays.toString(params)); int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { logger.debug("Server replied with a " + statusCode + " HTTP status code (" + HttpStatus.getStatusText(statusCode) + ")"); throw new SlideShareErrorException(statusCode, HttpStatus.getStatusText(statusCode)); } if (logger.isDebugEnabled()) { logger.debug(method.getResponseBodyAsString()); } InputStream result = new ByteArrayInputStream(method.getResponseBody()); method.releaseConnection(); return result; }