protected String getRallyXML(String apiUrl) throws Exception { String responseXML = ""; DefaultHttpClient httpClient = new DefaultHttpClient(); Base64 base64 = new Base64(); String encodeString = new String(base64.encode((rallyApiHttpUsername + ":" + rallyApiHttpPassword).getBytes())); HttpGet httpGet = new HttpGet(apiUrl); httpGet.addHeader("Authorization", "Basic " + encodeString); HttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); if (entity != null) { InputStreamReader reader = new InputStreamReader(entity.getContent()); BufferedReader br = new BufferedReader(reader); StringBuilder sb = new StringBuilder(); String line = ""; while ((line = br.readLine()) != null) { sb.append(line); } responseXML = sb.toString(); } log.debug("responseXML=" + responseXML); return responseXML; }
private String sendBasic(HttpRequestBase request) throws HttpException { try { HttpResponse response = httpClient.execute(request); HttpEntity entity = response.getEntity(); String body = ""; if (entity != null) { body = EntityUtils.toString(entity, UTF_8); if (entity.getContentType() == null) { body = new String(body.getBytes(ISO_8859_1), UTF_8); } } int code = response.getStatusLine().getStatusCode(); if (code < 200 || code >= 300) { throw new Exception(String.format(" code : '%s' , body : '%s'", code, body)); } return body; } catch (Exception ex) { throw new HttpException( "Fail to send " + request.getMethod() + " request to url " + request.getURI() + ", " + ex.getMessage(), ex); } finally { request.releaseConnection(); } }
public Result<InputStream> getInputStream(String endpoint) throws IOException { HttpClient cli = createClient(); HttpGet get = createGet(endpoint); HttpResponse res = cli.execute(get); Object result = null; if (res.getStatusLine().getStatusCode() == 200) result = res.getEntity().getContent(); else { RestResponse resp = new RestResponse(res); result = unmarshalPOJO(resp, InputStream.class); cli.getConnectionManager().shutdown(); } return new Result<InputStream>(result); }
/** * Parse the room read response received from reservation backend. * * <p>This will request the retry if the response status code differs from 200, 201 or 4xx. * * @param response The Apache HTTP client response * @throws IOException * @throws ParseException * @throws FaultTolerantRESTRequest.RetryRequestedException */ @Override protected void parse(HttpResponse response) throws IOException, ParseException, FaultTolerantRESTRequest.RetryRequestedException { int statusCode = response.getStatusLine().getStatusCode(); logger.info("STATUS CODE: " + statusCode); if (200 == statusCode || 201 == statusCode) { // OK conference = readConferenceResponse(conference, response); result = new ApiResult(statusCode, conference); } else if ((statusCode >= 400) && (statusCode < 500)) { // Client side error, indicates that the reservation // backend do not want the resubmission ErrorResponse error = readErrorResponse(response); result = new ApiResult(statusCode, error); } else { // Unusual status code, request the retry throw new FaultTolerantRESTRequest.RetryRequestedException(); } }
public Either<IOException, InputStream> apply(HttpResponse resp) { try { return new Right<IOException, InputStream>(resp.getEntity().getContent()); } catch (IOException e) { return new Left<IOException, InputStream>(e); } }
/** @return {@link InputStream} from a {@link HttpResponse} */ InputStream getStream(HttpResponse response) { try { return response.getEntity().getContent(); } catch (Exception e) { log.error("Error reading response. " + e.getMessage()); throw new CouchDbException(e); } }
/** * Parses error response. * * @param response parsed <tt>ErrorResponse</tt> * @return <tt>ErrorResponse</tt> parsed from HTTP content stream. * @throws IOException if any IO issues occur. * @throws ParseException if any issues with JSON parsing occur. */ private ErrorResponse readErrorResponse(HttpResponse response) throws IOException, ParseException { BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); jsonParser.parse(rd, errorJson); return errorJson.getResult(); }
protected String postRallyXML(String apiUrl, String requestXML) throws Exception { String responseXML = ""; DefaultHttpClient httpClient = new DefaultHttpClient(); Base64 base64 = new Base64(); String encodeString = new String(base64.encode((rallyApiHttpUsername + ":" + rallyApiHttpPassword).getBytes())); HttpPost httpPost = new HttpPost(apiUrl); httpPost.addHeader("Authorization", "Basic " + encodeString); httpPost.setEntity(new StringEntity(requestXML)); HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); responseXML = getEntityString(entity); return responseXML; }
public Either<IOException, HttpResponse> execRequest(HttpUriRequest httpReq, String acceptType) { DefaultHttpClient httpClient = new DefaultHttpClient(); httpReq.setHeader("accept", acceptType); for (Header header : getHeaders()) { httpReq.setHeader(header); } try { HttpResponse resp = httpClient.execute(httpReq); Log.i( TAG, String.format( "%s %s %s => %d", httpReq.getRequestLine().getMethod(), httpReq.getRequestLine().getUri(), httpReq.getParams(), resp.getStatusLine().getStatusCode())); return new Right<IOException, HttpResponse>(resp); } catch (IOException e) { return new Left<IOException, HttpResponse>(e); } }
/** * Validates a HTTP response; on error cases logs status and throws relevant exceptions. * * @param response The HTTP response. */ private void validate(HttpResponse response) throws IOException { int code = response.getStatusLine().getStatusCode(); if (code == 200 || code == 201 || code == 202) { // success (ok | created | accepted) return; } String msg = format("<< Status: %s (%s) ", code, response.getStatusLine().getReasonPhrase()); switch (code) { case HttpStatus.SC_NOT_FOUND: { log.info(msg); throw new NoDocumentException(msg); } case HttpStatus.SC_CONFLICT: { log.warn(msg); throw new DocumentConflictException(msg); } default: { // other errors: 400 | 401 | 500 etc. log.error(msg += EntityUtils.toString(response.getEntity())); throw new CouchDbException(msg); } } }
public Either<IOException, String> apply(HttpResponse response) { BufferedReader reader = null; try { StringBuilder builder = new StringBuilder(); reader = new BufferedReader( new InputStreamReader(response.getEntity().getContent(), "UTF-8")); while (true) { String read = reader.readLine(); if (read == null) break; builder.append(read); } return new Right<IOException, String>(builder.toString()); } catch (IOException e) { return new Left<IOException, String>(e); } }
/** * Parses JSON string returned in HTTP response and converts it to <tt>Conference</tt> instance. * * @param conference <tt>Conference</tt> instance that contains the data returned by API endpoint. * @param response HTTP response returned by the API endpoint. * @return <tt>Conference</tt> instance that contains the data returned by API endpoint. * @throws IOException if any IO problems occur. * @throws ParseException if any problems with JSON parsing occur. */ private Conference readConferenceResponse(Conference conference, HttpResponse response) throws IOException, ParseException { BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); if (conference != null) { conferenceJson.setForUpdate(conference); } jsonParser.parse(rd, conferenceJson); if (conference == null) { conference = conferenceJson.getResult(); } logger.info("ID: " + conference.getId()); logger.info("PIN: " + conference.getPin()); logger.info("URL: " + conference.getUrl()); logger.info("SIP ID: " + conference.getSipId()); logger.info("START TIME: " + conference.getStartTime()); logger.info("DURATION: " + conference.getDuration()); return conference; }
/** 连接网络读取数据 */ @Override protected <T> void connectWithRetries(AbstractRequest<T> request, InternalResponse response) throws HttpClientException, HttpNetException, HttpServerException { // if(true) { // throw new HttpNetException(NetException.NetworkDisabled); // } // 1. create apache request final HttpUriRequest apacheRequest = createApacheRequest(request); // 2. update http header if (request.getHeaders() != null) { Set<Entry<String, String>> set = request.getHeaders().entrySet(); for (Entry<String, String> en : set) { apacheRequest.setHeader(new BasicHeader(en.getKey(), en.getValue())); } } // 3. try to connect HttpListener<T> listener = request.getHttpListener(); StatisticsListener statistic = response.getStatistics(); int times = 0, maxRetryTimes = request.getMaxRetryTimes(), maxRedirectTimes = request.getMaxRedirectTimes(); boolean retry = true; IOException cause = null; while (retry) { try { cause = null; retry = false; if (request.isCancelledOrInterrupted()) { return; } if (statistic != null) { statistic.onPreConnect(request); } HttpResponse ares = mHttpClient.execute(apacheRequest); if (statistic != null) { statistic.onAfterConnect(request); } // status StatusLine status = ares.getStatusLine(); HttpStatus httpStatus = new HttpStatus(status.getStatusCode(), status.getReasonPhrase()); response.setHttpStatus(httpStatus); // header Header[] headers = ares.getAllHeaders(); if (headers != null) { com.litesuits.http.data.NameValuePair hs[] = new com.litesuits.http.data.NameValuePair[headers.length]; for (int i = 0; i < headers.length; i++) { String name = headers[i].getName(); String value = headers[i].getValue(); if ("Content-Length".equalsIgnoreCase(name)) { response.setContentLength(Long.parseLong(value)); } hs[i] = new com.litesuits.http.data.NameValuePair(name, value); } response.setHeaders(hs); } // data body if (status.getStatusCode() <= 299 || status.getStatusCode() == 600) { // 成功 HttpEntity entity = ares.getEntity(); if (entity != null) { // charset String charSet = getCharsetFromEntity(entity, request.getCharSet()); response.setCharSet(charSet); // is cancelled ? if (request.isCancelledOrInterrupted()) { return; } // length long len = response.getContentLength(); DataParser<T> parser = request.getDataParser(); if (statistic != null) { statistic.onPreRead(request); } parser.readFromNetStream(entity.getContent(), len, charSet); if (statistic != null) { statistic.onAfterRead(request); } response.setReadedLength(parser.getReadedLength()); endEntityViaReflection(entity); } return; } else if (status.getStatusCode() <= 399) { // redirect if (response.getRedirectTimes() < maxRedirectTimes) { // get the location header to find out where to redirect to Header locationHeader = ares.getFirstHeader(Consts.REDIRECT_LOCATION); if (locationHeader != null) { String location = locationHeader.getValue(); if (location != null && location.length() > 0) { if (!location.toLowerCase().startsWith("http")) { URI uri = new URI(request.getFullUri()); URI redirect = new URI(uri.getScheme(), uri.getHost(), location, null); location = redirect.toString(); } response.setRedirectTimes(response.getRedirectTimes() + 1); request.setUri(location); if (HttpLog.isPrint) { HttpLog.i(TAG, "Redirect to : " + location); } if (listener != null) { listener.notifyCallRedirect( request, maxRedirectTimes, response.getRedirectTimes()); } connectWithRetries(request, response); return; } } throw new HttpServerException(httpStatus); } else { throw new HttpServerException(ServerException.RedirectTooMuch); } } else if (status.getStatusCode() <= 499) { // 客户端被拒 throw new HttpServerException(httpStatus); } else if (status.getStatusCode() < 599) { // 服务器有误 throw new HttpServerException(httpStatus); } } catch (IOException e) { cause = e; } catch (NullPointerException e) { // bug in HttpClient 4.0.x, see http://code.google.com/p/android/issues/detail?id=5255 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) { cause = new IOException(e.getMessage()); } else { cause = new IOException(e); } } catch (URISyntaxException e) { throw new HttpClientException(e); } catch (IllegalStateException e) { // for apache http client. if url is illegal, it usually raises an exception as // "IllegalStateException: // Scheme 'xxx' not registered." throw new HttpClientException(e); } catch (SecurityException e) { throw new HttpClientException(e, ClientException.PermissionDenied); } catch (RuntimeException e) { throw new HttpClientException(e); } if (cause != null) { try { if (request.isCancelledOrInterrupted()) { return; } times++; retry = retryHandler.retryRequest( cause, times, maxRetryTimes, mHttpContext, config.getContext()); } catch (InterruptedException e) { e.printStackTrace(); return; } if (retry) { response.setRetryTimes(times); if (HttpLog.isPrint) { HttpLog.i(TAG, "LiteHttp retry request: " + request.getUri()); } if (listener != null) { listener.notifyCallRetry(request, maxRetryTimes, times); } } } } if (cause != null) { throw new HttpNetException(cause); } }
public void tempRedirectInvoke( @Nonnull String tempEndpoint, @Nonnull String method, @Nonnull String account, @Nonnull String resource, @Nonnull String body) throws CloudException, InternalException { if (logger.isTraceEnabled()) { logger.trace( "enter - " + AzureMethod.class.getName() + ".post(" + account + "," + resource + ")"); } if (wire.isDebugEnabled()) { wire.debug( "POST --------------------------------------------------------> " + endpoint + account + resource); wire.debug(""); } try { HttpClient client = getClient(); String url = tempEndpoint + account + resource; HttpRequestBase httpMethod = getMethod(method, url); // If it is networking configuration services if (httpMethod instanceof HttpPut) { if (url.endsWith("/services/networking/media")) { httpMethod.addHeader("Content-Type", "text/plain"); } else { httpMethod.addHeader("Content-Type", "application/xml;charset=UTF-8"); } } else { httpMethod.addHeader("Content-Type", "application/xml;charset=UTF-8"); } // dmayne version is older for anything to do with images and for disk deletion if (url.indexOf("/services/images") > -1 || (httpMethod instanceof HttpDelete && url.indexOf("/services/disks") > -1)) { httpMethod.addHeader("x-ms-version", "2012-08-01"); } else { httpMethod.addHeader("x-ms-version", "2012-03-01"); } if (strategy != null && strategy.getSendAsHeader()) { httpMethod.addHeader(strategy.getHeaderName(), strategy.getRequestId()); } if (wire.isDebugEnabled()) { wire.debug(httpMethod.getRequestLine().toString()); for (Header header : httpMethod.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); if (body != null) { wire.debug(body); wire.debug(""); } } if (httpMethod instanceof HttpEntityEnclosingRequestBase) { HttpEntityEnclosingRequestBase entityEnclosingMethod = (HttpEntityEnclosingRequestBase) httpMethod; if (body != null) { try { entityEnclosingMethod.setEntity(new StringEntity(body, "application/xml", "utf-8")); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } HttpResponse response; StatusLine status; try { response = client.execute(httpMethod); status = response.getStatusLine(); } catch (IOException e) { logger.error( "post(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage()); if (logger.isTraceEnabled()) { e.printStackTrace(); } throw new CloudException(e); } if (logger.isDebugEnabled()) { logger.debug("post(): HTTP Status " + status); } Header[] headers = response.getAllHeaders(); if (wire.isDebugEnabled()) { wire.debug(status.toString()); for (Header h : headers) { if (h.getValue() != null) { wire.debug(h.getName() + ": " + h.getValue().trim()); } else { wire.debug(h.getName() + ":"); } } wire.debug(""); } if (status.getStatusCode() != HttpServletResponse.SC_OK && status.getStatusCode() != HttpServletResponse.SC_CREATED && status.getStatusCode() != HttpServletResponse.SC_ACCEPTED) { logger.error("post(): Expected OK for GET request, got " + status.getStatusCode()); HttpEntity entity = response.getEntity(); if (entity == null) { throw new AzureException( CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), "An error was returned without explanation"); } try { body = EntityUtils.toString(entity); } catch (IOException e) { throw new AzureException( CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } if (wire.isDebugEnabled()) { wire.debug(body); } wire.debug(""); AzureException.ExceptionItems items = AzureException.parseException(status.getStatusCode(), body); if (items == null) { throw new CloudException( CloudErrorType.GENERAL, status.getStatusCode(), "Unknown", "Unknown"); } logger.error( "post(): [" + status.getStatusCode() + " : " + items.message + "] " + items.details); throw new AzureException(items); } } finally { if (logger.isTraceEnabled()) { logger.trace("exit - " + AzureMethod.class.getName() + ".post()"); } if (wire.isDebugEnabled()) { wire.debug(""); wire.debug( "POST --------------------------------------------------------> " + endpoint + account + resource); } } }
public String post(@Nonnull String account, @Nonnull String resource, @Nonnull String body) throws CloudException, InternalException { if (logger.isTraceEnabled()) { logger.trace( "enter - " + AzureMethod.class.getName() + ".post(" + account + "," + resource + ")"); } if (wire.isDebugEnabled()) { wire.debug( "POST --------------------------------------------------------> " + endpoint + account + resource); wire.debug(""); } String requestId = null; try { HttpClient client = getClient(); String url = endpoint + account + resource; HttpPost post = new HttpPost(url); if (url.toLowerCase().contains("operations")) { post.addHeader("x-ms-version", "2014-02-01"); } else if (url.toLowerCase().contains("/deployments")) { post.addHeader("x-ms-version", "2014-05-01"); } else { post.addHeader("x-ms-version", "2012-03-01"); } if (strategy != null && strategy.getSendAsHeader()) { post.addHeader(strategy.getHeaderName(), strategy.getRequestId()); } // If it is networking configuration services if (url.endsWith("/services/networking/media")) { post.addHeader("Content-Type", "text/plain;charset=UTF-8"); } else { post.addHeader("Content-Type", "application/xml;charset=UTF-8"); } if (wire.isDebugEnabled()) { wire.debug(post.getRequestLine().toString()); for (Header header : post.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); if (body != null) { wire.debug(body); wire.debug(""); } } if (body != null) { try { if (url.endsWith("/services/networking/media")) { post.setEntity(new StringEntity(body, "text/plain", "utf-8")); } else { post.setEntity(new StringEntity(body, "application/xml", "utf-8")); } } catch (UnsupportedEncodingException e) { throw new InternalException(e); } } HttpResponse response; StatusLine status; try { response = client.execute(post); status = response.getStatusLine(); } catch (IOException e) { logger.error( "post(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage()); if (logger.isTraceEnabled()) { e.printStackTrace(); } throw new CloudException(e); } if (logger.isDebugEnabled()) { logger.debug("post(): HTTP Status " + status); } Header[] headers = response.getAllHeaders(); if (wire.isDebugEnabled()) { wire.debug(status.toString()); } for (Header h : headers) { if (h.getValue() != null) { if (wire.isDebugEnabled()) { wire.debug(h.getName() + ": " + h.getValue().trim()); } if (h.getName().equalsIgnoreCase("x-ms-request-id")) { requestId = h.getValue().trim(); } } else { if (wire.isDebugEnabled()) { wire.debug(h.getName() + ":"); } } } if (wire.isDebugEnabled()) { wire.debug(""); } if (status.getStatusCode() != HttpServletResponse.SC_OK && status.getStatusCode() != HttpServletResponse.SC_CREATED && status.getStatusCode() != HttpServletResponse.SC_ACCEPTED) { logger.error("post(): Expected OK for GET request, got " + status.getStatusCode()); HttpEntity entity = response.getEntity(); if (entity == null) { throw new AzureException( CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), "An error was returned without explanation"); } try { body = EntityUtils.toString(entity); } catch (IOException e) { throw new AzureException( CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } if (wire.isDebugEnabled()) { wire.debug(body); } wire.debug(""); AzureException.ExceptionItems items = AzureException.parseException(status.getStatusCode(), body); if (items == null) { throw new CloudException( CloudErrorType.GENERAL, status.getStatusCode(), "Unknown", "Unknown"); } logger.error( "post(): [" + status.getStatusCode() + " : " + items.message + "] " + items.details); throw new AzureException(items); } } finally { if (logger.isTraceEnabled()) { logger.trace("exit - " + AzureMethod.class.getName() + ".post()"); } if (wire.isDebugEnabled()) { wire.debug(""); wire.debug( "POST --------------------------------------------------------> " + endpoint + account + resource); } } return requestId; }
public @Nullable InputStream getAsStream(@Nonnull String account, @Nonnull URI uri) throws CloudException, InternalException { logger.trace("enter - " + AzureMethod.class.getName() + ".get(" + account + "," + uri + ")"); wire.debug("--------------------------------------------------------> " + uri.toASCIIString()); try { HttpClient client = getClient(); HttpUriRequest get = new HttpGet(uri); if (uri.toString().indexOf("/services/images") > -1) { get.addHeader("x-ms-version", "2012-08-01"); } else if (uri.toString().contains("/services/vmimages")) { get.addHeader("x-ms-version", "2014-05-01"); } else { get.addHeader("x-ms-version", "2012-03-01"); } if (strategy != null && strategy.getSendAsHeader()) { get.addHeader(strategy.getHeaderName(), strategy.getRequestId()); } wire.debug(get.getRequestLine().toString()); for (Header header : get.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } HttpResponse response; StatusLine status; try { response = client.execute(get); status = response.getStatusLine(); } catch (IOException e) { logger.error( "get(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage()); throw new CloudException(e); } logger.debug("get(): HTTP Status " + status); Header[] headers = response.getAllHeaders(); wire.debug(status.toString()); for (Header h : headers) { if (h.getValue() != null) { wire.debug(h.getName() + ": " + h.getValue().trim()); } else { wire.debug(h.getName() + ":"); } } if (status.getStatusCode() == HttpServletResponse.SC_NOT_FOUND) { return null; } if (status.getStatusCode() != HttpServletResponse.SC_OK && status.getStatusCode() != HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION) { logger.error("get(): Expected OK for GET request, got " + status.getStatusCode()); HttpEntity entity = response.getEntity(); String body; if (entity == null) { throw new AzureException( CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), "An error was returned without explanation"); } try { body = EntityUtils.toString(entity); } catch (IOException e) { throw new AzureException( CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } wire.debug(body); AzureException.ExceptionItems items = AzureException.parseException(status.getStatusCode(), body); if (items == null) { return null; } logger.error( "get(): [" + status.getStatusCode() + " : " + items.message + "] " + items.details); throw new AzureException(items); } else { HttpEntity entity = response.getEntity(); if (entity == null) { return null; } InputStream input; try { input = entity.getContent(); } catch (IOException e) { logger.error( "get(): Failed to read response error due to a cloud I/O error: " + e.getMessage()); throw new CloudException(e); } wire.debug("---> Binary Data <---"); return input; } } finally { logger.trace("exit - " + AzureMethod.class.getName() + ".getStream()"); wire.debug( "--------------------------------------------------------> " + uri.toASCIIString()); } }