List of usage examples for org.apache.http.client ClientProtocolException getMessage
public String getMessage()
From source file:com.tomdignan.android.opencnam.library.teststub.test.OpenCNAMRequestTestCase.java
public void testXMLRequest() { mOpenCNAMRequest.setSerializationFormat(OpenCNAMRequest.FORMAT_XML); // TEXT is default. String response = null;/* w w w.j av a2 s .co m*/ try { response = (String) mOpenCNAMRequest.execute(); } catch (ClientProtocolException e) { Log.e(TAG, "ClientProtocolException: " + e.getMessage()); } catch (IOException e) { Log.e(TAG, "ClientProtocolException: " + e.getMessage()); } assertNotNull(response); ByteArrayInputStream inputStream = new ByteArrayInputStream(response.getBytes()); Document document = null; try { document = mDocumentBuilder.parse(inputStream); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } assertNotNull(document); Element root = document.getDocumentElement(); String rootName = root.getNodeName(); assertNotNull(rootName); assertEquals(rootName, "object"); NodeList children = root.getChildNodes(); assertNotNull(children); int size = children.getLength(); assertEquals(size, 2); Node cnamNode = children.item(0); assertNotNull(cnamNode); String cnamValue = cnamNode.getTextContent().trim(); assertEquals(cnamValue, CNAM); String cnamNodeName = cnamNode.getNodeName(); assertEquals(cnamNodeName, "cnam"); Node numberNode = children.item(1); assertNotNull(numberNode); String numberName = numberNode.getNodeName().trim(); assertNotNull(numberName); assertEquals(numberName, "number"); String numberValue = numberNode.getTextContent().trim(); assertNotNull(numberValue); assertEquals(numberValue, NUMBER); }
From source file:com.mnxfst.testing.handler.exec.client.PTestPlanExecutorClientCallable.java
/** * @see java.util.concurrent.Callable#call() */// www .ja va 2 s.c o m public NameValuePair call() throws Exception { InputStream ptestServerInputStream = null; try { HttpResponse httpResponse = httpClient.execute(httpHost, postMethod); ptestServerInputStream = httpResponse.getEntity().getContent(); PTestPlanExecutionStartedResponse response = PTestPlanExecutorResponseBuilder .buildTestplanExecutionStartedResponse(ptestServerInputStream); if (response.getResponseCode() != null && response.getResponseCode().intValue() == PTestPlanExecutionStartedResponse.RESPONSE_OK) { return new BasicNameValuePair(httpHost.getHostName(), response.getResultIdentifier()); } else { StringBuffer errors = new StringBuffer(); for (Iterator<String> keyIter = response.getErrors().keySet().iterator(); keyIter.hasNext();) { String errKey = keyIter.next(); errors.append(errKey); if (keyIter.hasNext()) errors.append(", "); } throw new RuntimeException("Failed to execute test plan on " + httpHost.getHostName() + ":" + httpHost.getPort() + ". Errors: " + errors.toString()); } } catch (ClientProtocolException e) { throw new RuntimeException("Failed to call " + httpHost.getHostName() + ":" + httpHost.getPort() + "/" + postMethod.getURI() + ". Error: " + e.getMessage()); } catch (IOException e) { throw new RuntimeException("Failed to call " + httpHost.getHostName() + ":" + httpHost.getPort() + "/" + postMethod.getURI() + ". Error: " + e.getMessage()); } finally { if (ptestServerInputStream != null) { try { ptestServerInputStream.close(); httpClient.getConnectionManager().shutdown(); } catch (Exception e) { System.out.println("Failed to close ptest-server connection"); } } } }
From source file:test.yhc.ytdn.NetLoader.java
public HttpRespContent getHttpContent(URI uri, boolean source) throws YTDNException { if (null == mHttpClient) { logI("NetLoader Fail to get HttpClient"); throw new YTDNException(Err.YTHTTPGET); }/*from w w w . j a va2s. co m*/ String uriString = uri.toString(); if (source) uriString = uriString.replace(uri.getScheme() + "://" + uri.getHost(), ""); int retry = 3; while (0 < retry--) { try { HttpGet httpGet = new HttpGet(uriString); HttpHost httpTarget = new HttpHost(uri.getHost()); logI("executing request: " + httpGet.getRequestLine().toString()); //logI("uri: " + httpGet.getURI().toString()); //logI("target: " + httpTarget.getHostName()); HttpResponse httpResp = mHttpClient.execute(httpTarget, httpGet); logI("NetLoader HTTP response status line : " + httpResp.getStatusLine().toString()); // TODO // Need more case-handling-code. // Ex. Redirection etc. int statusCode = httpResp.getStatusLine().getStatusCode(); switch (statusCode) { case HttpUtils.SC_OK: case HttpUtils.SC_NO_CONTENT: ;// expected response. let's move forward break; default: // Unexpected response logI("NetLoader Unexpected Response status code : " + httpResp.getStatusLine().getStatusCode()); throw new YTDNException(Err.YTHTTPGET); } InputStream contentStream = null; String contentType = null; if (HttpUtils.SC_NO_CONTENT == statusCode) { ; } else { HttpEntity httpEntity = httpResp.getEntity(); if (null == httpEntity) { logI("NetLoader Unexpected NULL entity"); throw new YTDNException(Err.YTHTTPGET); } contentStream = httpEntity.getContent(); contentType = httpResp.getFirstHeader("Content-Type").getValue().toLowerCase(); } return new HttpRespContent(statusCode, contentStream, contentType); } catch (ClientProtocolException e) { logI("NetLoader ClientProtocolException : " + e.getMessage()); throw new YTDNException(Err.YTHTTPGET); } catch (UnknownHostException e) { logI("NetLoader UnknownHostException : Maybe timeout?" + e.getMessage()); if (mUserClose) throw new YTDNException(Err.CANCELLED); if (0 >= retry) throw new YTDNException(Err.IO_NET); ; // continue next retry after some time. try { Thread.sleep(300); } catch (InterruptedException ie) { if (mUserClose) throw new YTDNException(Err.CANCELLED); else throw new YTDNException(Err.INTERRUPTED); } throw new YTDNException(Err.YTHTTPGET); } catch (IOException e) { logW("NetLoader IOException : " + e.getMessage()); throw new YTDNException(Err.YTHTTPGET); } catch (IllegalStateException e) { logW("NetLoader IllegalStateException : " + e.getMessage()); throw new YTDNException(Err.YTHTTPGET); } } eAssert(false); return null; }
From source file:eu.europeanaconnect.erds.HTTPResolverMultiThreaded.java
/** * Fetches the URL out of the header of the redirect response * of the remote resolver using the "Location" attribute * //from w w w .j a v a 2 s. c o m * @see DataProvider#getResponse(ResolverRequest) * @since 17.03.2010 */ @Override public ResolverResponse getResponse(ResolverRequest resolverRequest) throws ResolverException { ResolverResponse resolverResponse = new ResolverResponse(); HttpResponse httpResponse = null; String url = getRequestUrl(resolverRequest); logger.debug("URL = " + url); HttpGet getMethod = new HttpGet(url); try { httpResponse = this.httpClient.execute(getMethod); logger.debug("Operation GET successfull"); } catch (ClientProtocolException e) { logger.error("A ClientProtocolException occured!\nStacktrace:\n" + e.getMessage()); e.printStackTrace(); throw new ResolverException(this.id, ResolverExceptionCode.HTTP_PROTOCOL_ERROR, e); } catch (IOException e) { logger.error("An IOException occured!\nStacktrace:\n" + e.getMessage()); e.printStackTrace(); throw new ResolverException(this.id, ResolverExceptionCode.IO_ERROR, e); } catch (RuntimeException e) { logger.error("A RuntimeException occured!\nStacktrace:\n" + e.getMessage()); e.printStackTrace(); throw new ResolverException(this.id, ResolverExceptionCode.SEVERE_RUNTIME_ERROR, e); } catch (Exception e) { logger.error("An Exception occured!\nStacktrace:\n" + e.getMessage()); e.printStackTrace(); throw new ResolverException(this.id, ResolverExceptionCode.UNKNOWN_ERROR, e); } StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); logger.debug("HTTP Status-code: " + statusCode); if ((statusCode > 299) && (statusCode < 400)) { //It is a redirect See: http://www.w3.org/Protocols/rfc2616/rfc2616.html logger.debug("Its a redirect: analyzing the HTTP Header"); //logger.debug(getMethod.) if (!httpResponse.containsHeader("Location")) { logger.error("Header does not contain Location attribute!"); throw new ResolverException(this.id, ResolverExceptionCode.NO_REDIRECT_ERROR); } logger.debug("Analyzing redirect location"); Header location = httpResponse.getFirstHeader("Location"); if (location == null) { logger.error("No redirect header for URL: " + url); throw new ResolverException(this.id, ResolverExceptionCode.NO_REDIRECT_ERROR); } logger.debug("Location: " + location.getValue()); resolverResponse.setUrl(location.getValue()); } else { if (statusCode < 300) { //that was not an identifier but a real link resolverResponse.setUrl(url); } else { //server returned a 4xx or 5xx code -> handle the error handleHttpErrorCodes(statusCode); } } return resolverResponse; }
From source file:org.openbmap.soapclient.FileUploader.java
/** * @param file/* ww w . j a v a 2 s . c o m*/ * @return */ private boolean performUpload(final String file) { // TODO check network state // @see http://developer.android.com/training/basics/network-ops/connecting.html // Adjust HttpClient parameters final HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. // The default value is zero, that means the timeout is not used. //HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTION_TIMEOUT); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. //HttpConnectionParams.setSoTimeout(httpParameters, SOCKET_TIMEOUT); final DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters); final HttpPost httppost = new HttpPost(mServer); try { final String authorizationString = "Basic " + Base64.encodeToString((mUser + ":" + mPassword).getBytes(), Base64.NO_WRAP); httppost.setHeader("Authorization", authorizationString); final MultipartEntity entity = new MultipartEntity(); // TODO we don't need passwords for the new service entity.addPart(LOGIN_FIELD, new StringBody(mUser)); entity.addPart(PASSWORD_FIELD, new StringBody(mPassword)); entity.addPart(FILE_FIELD, new FileBody(new File(file), "text/xml")); httppost.setEntity(entity); final HttpResponse response = httpclient.execute(httppost); final int reply = response.getStatusLine().getStatusCode(); if (reply == 200) { Log.i(TAG, "Uploaded " + file + ": Server reply " + reply); } else { Log.w(TAG, "Error while uploading" + file + ": Server reply " + reply); } // everything is ok if we receive HTTP 200 // TODO: redirects (301, 302) are NOT handled here // thus if something changes on the server side we're dead here return (reply == HttpStatus.SC_OK); } catch (final ClientProtocolException e) { Log.e(TAG, e.getMessage()); } catch (final IOException e) { Log.e(TAG, "I/O exception on file " + file); } return false; }
From source file:com.buession.cas.client.RestfulAuthentication.java
/** * //from w w w . j a v a2s . c om * * @param ticketGrantingTicket * Ticket Granting Ticket * @return boolean */ public boolean logout(final String ticketGrantingTicket) { Validate.notBlank(ticketGrantingTicket, "TicketGrantingTicket could not be null or empty"); final String url = configuration.getServer() + "/v1/tickets/" + ticketGrantingTicket; final HttpDelete httpDelete = new HttpDelete(url); httpDelete.setConfig(requestConfig); try { HttpResponse response = httpClient.execute(httpDelete); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode >= 200 && statusCode < 300) { return true; } else { logger.warn("Invalid response code \"{}\" from CASServer", statusCode); } } catch (ClientProtocolException e) { logger.error(e.getMessage()); } catch (IOException e) { logger.error(e.getMessage()); } finally { httpDelete.releaseConnection(); } return false; }
From source file:api.WebServiceCommand.java
@Override public CommandStatus execute() { CommandStatus status = new CommandStatus(); try {// w ww. j a va 2 s .co m switch (this.httpVerb) { case "POST": status = Request.Post(this.uri).version(this.version).useExpectContinue() .connectTimeout(this.connectionTimeout).socketTimeout(this.socketTimeout) .bodyString(this.postString, this.contentType).execute() .handleResponse(new ResponseHandler<HTTPCommandStatus>() { @Override public HTTPCommandStatus handleResponse(HttpResponse hr) throws ClientProtocolException, IOException { HTTPCommandStatus cs = new HTTPCommandStatus(); StatusLine statusLine = hr.getStatusLine(); HttpEntity entity = hr.getEntity(); cs.setHttpCode(statusLine.getStatusCode()); cs.setEntity(entity); cs.setStderr(statusLine.getReasonPhrase()); return cs; } }); case "GET": default: status = Request.Get(this.uri).version(this.version).connectTimeout(this.connectionTimeout) .socketTimeout(this.socketTimeout).execute() .handleResponse(new ResponseHandler<HTTPCommandStatus>() { @Override public HTTPCommandStatus handleResponse(HttpResponse hr) throws ClientProtocolException, IOException { HTTPCommandStatus cs = new HTTPCommandStatus(); StatusLine statusLine = hr.getStatusLine(); HttpEntity entity = hr.getEntity(); cs.setHttpCode(statusLine.getStatusCode()); cs.setEntity(entity); cs.setStderr(statusLine.getReasonPhrase()); return cs; } }); break; } if (this.debug) { System.out.println(" CODE RETURNED: '" + status.getStatus() + "'."); System.out.println("CONTOUT RETURNED: '" + status.getStdout() + "'."); System.out.println("CONTERR RETURNED: '" + status.getStderr() + "'."); } } catch (ClientProtocolException ex) { status.setEnded(ResponseTypes.CONFIG_ERROR.ordinal()); System.out.println(ex.getMessage()); } catch (IOException ex) { status.setEnded(ResponseTypes.FAIL.ordinal()); System.out.println(ex.getMessage()); } return status; }
From source file:at.fhooe.mcm.webdav.WebDavInterface.java
/** * executes a http post request//from ww w. j ava 2s . c o m * * also adds the user/password to the request params * * @param values * @return */ private RestResponse doRequest(List<NameValuePair> values) { HttpClient httpclient = new DefaultHttpClient(); // Prepare a request object HttpPost post = new HttpPost(url); // Execute the request String data = ""; int returnCode = -1; try { values.add(new BasicNameValuePair("user", user)); values.add(new BasicNameValuePair("pw", pw)); HttpEntity entity = new UrlEncodedFormEntity(values); post.setEntity(entity); HttpResponse response = httpclient.execute(post); // Examine the response status returnCode = response.getStatusLine().getStatusCode(); data = convertStreamToString(response.getEntity().getContent()); return new RestResponse(returnCode, data); } catch (ClientProtocolException e) { e.printStackTrace(); data = e.getClass().getName() + " " + e.getMessage(); } catch (IOException e) { e.printStackTrace(); data = e.getClass().getName() + " " + e.getMessage(); } return new RestResponse(-1, data); }
From source file:com.dfws.idea.ViewSourceActivity.java
protected String fileGetContents(String url) { String returnStr = ""; HttpGet httpGet = new HttpGet(url); HttpParams httpParams = new BasicHttpParams(); // Socket ? Socket ? HttpConnectionParams.setConnectionTimeout(httpParams, 20 * 1000); HttpConnectionParams.setSoTimeout(httpParams, 20 * 1000); HttpConnectionParams.setSocketBufferSize(httpParams, 8192); // ??? true//www . j a va 2s .c o m HttpClientParams.setRedirecting(httpParams, true); // user agent String userAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2) Gecko/20100115 Firefox/3.6"; HttpProtocolParams.setUserAgent(httpParams, userAgent); HttpClient httpClient = new DefaultHttpClient(httpParams); try { HttpResponse response = httpClient.execute(httpGet); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == ClosePcActivity.OK_STATUS_CODE) { // ? returnStr = EntityUtils.toString(response.getEntity()); } else { Toast.makeText(ViewSourceActivity.this, "???", Toast.LENGTH_SHORT).show(); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block String strResult = e.getMessage().toString(); Log.i("test", strResult); e.printStackTrace(); } return returnStr; }
From source file:org.openbmap.soapclient.AsyncUploader.java
/** * Sends an authenticated http post request to upload file * @param file File to upload (full path) * @return true on response code 200, false otherwise *///w w w.ja va2s . c o m private UploadResult httpPostRequest(final String file) { // TODO check network state // @see http://developer.android.com/training/basics/network-ops/connecting.html // Adjust HttpClient parameters final HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. // The default value is zero, that means the timeout is not used. // HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTION_TIMEOUT); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. //HttpConnectionParams.setSoTimeout(httpParameters, SOCKET_TIMEOUT); final DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters); final HttpPost httppost = new HttpPost(mServer); try { final MultipartEntity entity = new MultipartEntity(); entity.addPart(FILE_FIELD, new FileBody(new File(file), "text/xml")); if ((mUser != null) && (mPassword != null)) { final String authorizationString = "Basic " + Base64.encodeToString((mUser + ":" + mPassword).getBytes(), Base64.NO_WRAP); httppost.setHeader("Authorization", authorizationString); } if (mToken != null) { entity.addPart(API_FIELD, new StringBody(mToken)); } httppost.setEntity(entity); final HttpResponse response = httpclient.execute(httppost); final int reply = response.getStatusLine().getStatusCode(); if (reply == 200) { // everything is ok if we receive HTTP 200 mSize = entity.getContentLength(); Log.i(TAG, "Uploaded " + file + ": Server reply " + reply); return UploadResult.OK; } else if (reply == 401) { Log.e(TAG, "Wrong username or password"); return UploadResult.WRONG_PASSWORD; } else { Log.w(TAG, "Error while uploading" + file + ": Server reply " + reply); return UploadResult.ERROR; } // TODO: redirects (301, 302) are NOT handled here // thus if something changes on the server side we're dead here } catch (final ClientProtocolException e) { Log.e(TAG, e.getMessage()); } catch (final IOException e) { Log.e(TAG, "I/O exception on file " + file); } return UploadResult.UNDEFINED; }