/** * Test * * @throws Exception * Any exception */ @Test public void createMultiPartRequestContentWithDataTest() throws Exception { String string="FILE_DATA"; File file=File.createTempFile("temp_",".txt"); file.deleteOnExit(); byte[] input=string.getBytes(IOHelper.getDefaultEncoding()); IOHelper.writeFile(input,file); HTTPRequest httpRequest=new HTTPRequest(); ContentPart<?>[] parts=new ContentPart[5]; //make array bigger to simulate null parts parts[0]=new ContentPart<String>("string_part","TEST_DATA",ContentPartType.STRING); parts[1]=new ContentPart<String>("string_part2","TEST_DATA2",ContentPartType.STRING); parts[2]=new ContentPart<File>("file_part",file,ContentPartType.FILE); httpRequest.setContent(parts); HttpMethodBase method=this.client.createMethod("http://fax4j.org",HTTPMethod.POST); RequestEntity output=this.client.createMultiPartRequestContent(httpRequest,method); file.delete(); Assert.assertNotNull(output); Assert.assertEquals(MultipartRequestEntity.class,output.getClass()); }
/** * This function sets the header properties in the HTTP method. * * @param httpRequest * The HTTP request * @param httpMethodClient * The apache HTTP method */ protected void setupHTTPRequestHeaderProperties(HTTPRequest httpRequest,HttpMethodBase httpMethodClient) { //setup header properties Properties headerProperties=httpRequest.getHeaderProperties(); if(headerProperties!=null) { Iterator<Entry<Object,Object>> iterator=headerProperties.entrySet().iterator(); Entry<Object,Object> entry=null; while(iterator.hasNext()) { //get next entry entry=iterator.next(); //set header values httpMethodClient.addRequestHeader((String)entry.getKey(),(String)entry.getValue()); } } }
/** * Test * * @throws Exception * Any exception */ @Test public void setupHTTPRequestHeaderPropertiesWithDataTest() throws Exception { Properties headerProperties=new Properties(); headerProperties.setProperty("key1","value1"); headerProperties.setProperty("key2","value2"); headerProperties.setProperty("key3","value3"); HTTPRequest httpRequest=new HTTPRequest(); httpRequest.setHeaderProperties(headerProperties); HttpMethodBase method=this.client.createMethod("http://fax4j.org",HTTPMethod.GET); this.client.setupHTTPRequestHeaderProperties(httpRequest,method); Header[] headers=method.getRequestHeaders(); Assert.assertEquals(3,headers.length); Assert.assertEquals("value1",method.getRequestHeader("key1").getValue()); Assert.assertEquals("value2",method.getRequestHeader("key2").getValue()); Assert.assertEquals("value3",method.getRequestHeader("key3").getValue()); }
/** * When triggered, the wfs download service will call the Observations and Measurements WFS request, * get the GeoSciML? output and compress it into a zip file for download. The user will have to * first make a download request and come back to check the download status. When the download is * completed, a link will be provided to download the requested Observations and Measurements output * in zip format. * * This method will return a HTML stream * * @param serviceUrl The URL of the NVCLDataService * @param email The user's email address * @param boreholeId selected borehole id (use as feature id for filtering purpose) * @param omUrl The valid url for the Observations and Measurements WFS * @param typeName The url parameter for the wfs request * @return */ public HttpMethodBase getDownloadWFSMethod(String serviceUrl, String email, String boreholeId, String omUrl, String typeName) { GetMethod method = new GetMethod(urlPathConcat(serviceUrl, "downloadwfs.html")); ArrayList<NameValuePair> valuePairs = new ArrayList<NameValuePair>(); //set all of the parameters valuePairs.add(new NameValuePair("email", email)); valuePairs.add(new NameValuePair("boreholeid", boreholeId)); valuePairs.add(new NameValuePair("serviceurl", omUrl)); valuePairs.add(new NameValuePair("typename", typeName)); //attach them to the method method.setQueryString((NameValuePair[]) valuePairs.toArray(new NameValuePair[valuePairs.size()])); return method; }
/** * Get all boreholes from a given service url and return the response * @param serviceURL * @param bbox Set to the bounding box in which to fetch results, otherwise set it to null * @param restrictToIDList [Optional] A list of gml:id values that the resulting filter should restrict its search space to * @return * @throws Exception */ public WFSTransformedResponse getAllBoreholes(String serviceURL, String boreholeName, String custodian, String dateOfDrilling, int maxFeatures, FilterBoundingBox bbox, List<String> restrictToIDList) throws Exception { String filterString; BoreholeFilter nvclFilter = new BoreholeFilter(boreholeName, custodian, dateOfDrilling, restrictToIDList); if (bbox == null) { filterString = nvclFilter.getFilterStringAllRecords(); } else { filterString = nvclFilter.getFilterStringBoundingBox(bbox); } HttpMethodBase method = null; try { // Create a GetFeature request with an empty filter - get all method = this.generateWFSRequest(serviceURL, "gsml:Borehole", null, filterString, maxFeatures, null, ResultType.Results); String responseGml = this.httpServiceCaller.getMethodResponseAsString(method); String responseKml = this.wfsToKml.convert(responseGml, serviceURL); return new WFSTransformedResponse(responseGml, responseKml, method); } catch (Exception ex) { throw new PortalServiceException(method, ex); } }
/** * Test doing a mine filter and getting all mines * @throws Exception */ @Test public void testDoMineFilterAllMines() throws Exception { final String serviceURL = "http://localhost?"; final String mineName = ""; //to get all mines final HttpMethodBase mockMethod = context.mock(HttpMethodBase.class); final String expectedKML = "<kml/>"; final String expectedGML = "<gml/>"; context.checking(new Expectations() {{ allowing(mockMethod).getURI();will(returnValue(new URI(serviceURL, true))); oneOf(mineralOccurrenceService).getMinesGml(serviceURL, mineName, null, 0);will(returnValue(new WFSTransformedResponse(expectedGML, expectedKML, mockMethod))); }}); //call with updateCSWRecords dud url ModelAndView modelAndView = this.earthResourcesFilterController.doMineFilter(serviceURL, mineName, null, 0); //Ensure that we get a valid response testMAVResponse(modelAndView, new Boolean(true), expectedGML, expectedKML); }
/** * Gets all RDF concepts at the specified repository as a single JENA Model. The results * will be requested page by page until the entire repository has been traversed. * * @return * @throws PortalServiceException */ public Model getAllScalarConcepts() throws PortalServiceException { Model model = ModelFactory.createDefaultModel(); int pageNumber = 0; int pageSize = this.getPageSize(); //Request each page in turn - put the results into Model do { HttpMethodBase method = ((NvclVocabMethodMaker)sissVocMethodMaker).getAllScalars(getBaseUrl(), getRepository(), Format.Rdf, pageSize, pageNumber); if (requestPageOfConcepts(method, model)) { pageNumber++; } else { break; } } while (true); return model; }
/** * Tests that hylogger filter uses the correct functions when the underlying hylogger lookup returns no results. * * @throws Exception the exception */ @Test public void testHyloggerFilterNoDatasets() throws Exception { final String serviceUrl = "http://fake.com/wfs"; final String nameFilter = "filterBob"; final String custodianFilter = "filterCustodian"; final String filterDate = "1986-10-09"; final int maxFeatures = 10; final FilterBoundingBox bbox = new FilterBoundingBox("EPSG:4326", new double[] {1., 2.}, new double[] {3., 4.}); final boolean onlyHylogger = true; final HttpMethodBase mockHttpMethodBase = context.mock(HttpMethodBase.class); final URI httpMethodURI = new URI("http://example.com", true); context.checking(new Expectations() {{ oneOf(mockBoreholeService).discoverHyloggerBoreholeIDs(with(equal(mockCSWService)),with(any(CSWRecordsFilterVisitor.class))); will(returnValue(new ArrayList<String>())); allowing(mockHttpMethodBase).getURI(); will(returnValue(httpMethodURI)); }}); ModelAndView response = this.nvclController.doBoreholeFilter(serviceUrl, nameFilter, custodianFilter, filterDate, maxFeatures, bbox, onlyHylogger); Assert.assertFalse((Boolean) response.getModel().get("success")); }
/** * Given a list of parameters, call a service and get the Mineral Activity features as GML/KML * @param serviceURL * @param mineName * @param startDate * @param endDate * @param oreProcessed * @param producedMaterial * @param cutOffGrade * @param production * @param maxFeatures * @param bbox [Optional] the spatial bounds to constrain the result set * @return * @throws Exception */ public InputStream downloadMiningActivityGml(String serviceURL, String mineName, String startDate, String endDate, String oreProcessed, String producedMaterial, String cutOffGrade, String production, int maxFeatures, FilterBoundingBox bbox ) throws Exception { //create the filter MiningActivityFilter filter = new MiningActivityFilter(mineName, startDate, endDate, oreProcessed, producedMaterial, cutOffGrade, production); String filterString = generateFilterString(filter, bbox); HttpMethodBase method = generateWFSRequest(serviceURL, MINING_ACTIVITY_FEATURE_TYPE, null, filterString, maxFeatures, null, ResultType.Results); try { return httpServiceCaller.getMethodResponseAsStream(method,client); } catch (Exception ex) { throw new PortalServiceException(method, ex); } }
/** * Gets the GML/KML response for all mines matching the specified parameters * @param serviceUrl a Web Feature Service URL * @param mineName [Optional] The mine name to constrain the result set * @param bbox [Optional] the spatial bounds to constrain the result set * @param maxFeatures The maximum number of features to request * @return * @throws PortalServiceException */ public WFSTransformedResponse getMinesGml(String serviceUrl, String mineName, FilterBoundingBox bbox, int maxFeatures) throws PortalServiceException { MineFilter filter = new MineFilter(mineName); String filterString = generateFilterString(filter, bbox); HttpMethodBase method = null; try { method = generateWFSRequest(serviceUrl, MINE_FEATURE_TYPE, null, filterString, maxFeatures, null, ResultType.Results); String responseGml = httpServiceCaller.getMethodResponseAsString(method); String responseKml = gmlToKml.convert(responseGml, serviceUrl); return new WFSTransformedResponse(responseGml, responseKml, method); } catch (Exception ex) { throw new PortalServiceException(method, "Error when attempting to download Mines GML", ex); } }
/** * Test doing a mine filter and getting all mines * @throws Exception */ @Test public void testDoMineFilterSingleMine() throws Exception { final String serviceURL = "http://localhost?"; final String mineName = "mineName"; //to get all mines final HttpMethodBase mockMethod = context.mock(HttpMethodBase.class); final String expectedKML = "<kml/>"; final String expectedGML = "<gml/>"; context.checking(new Expectations() {{ allowing(mockMethod).getURI();will(returnValue(new URI(serviceURL, true))); oneOf(mineralOccurrenceService).getMinesGml(serviceURL, mineName, null, 0);will(returnValue(new WFSTransformedResponse(expectedGML, expectedKML, mockMethod))); }}); //call with updateCSWRecords dud url ModelAndView modelAndView = this.earthResourcesFilterController.doMineFilter(serviceURL, mineName, null, 0); //Ensure that we get a valid response testMAVResponse(modelAndView, new Boolean(true), expectedGML, expectedKML); }
/** * Given a list of parameters, call a service and get the count of Mineral Occurrence GML * @param serviceURL * @param commodityName * @param measureType * @param minOreAmount * @param minOreAmountUOM * @param minCommodityAmount * @param minCommodityAmountUOM * @param cutOffGrade * @param cutOffGradeUOM * @param bbox [Optional] the spatial bounds to constrain the result set * @return */ public WFSCountResponse getMineralOccurrenceCount(String serviceURL, String commodityName, String measureType, String minOreAmount, String minOreAmountUOM, String minCommodityAmount, String minCommodityAmountUOM, int maxFeatures, FilterBoundingBox bbox) throws PortalServiceException { MineralOccurrenceFilter filter = new MineralOccurrenceFilter(commodityName, measureType, minOreAmount, minOreAmountUOM, minCommodityAmount, minCommodityAmountUOM); String filterString = generateFilterString(filter, bbox); HttpMethodBase method = generateWFSRequest(serviceURL, MINERAL_OCCURRENCE_FEATURE_TYPE, null, filterString, maxFeatures, null, ResultType.Hits); return getWfsFeatureCount(method); }
/** * Given a list of parameters, call a service and get the count of Mineral Activity features * @param serviceURL * @param mineName * @param startDate * @param endDate * @param oreProcessed * @param producedMaterial * @param cutOffGrade * @param production * @param maxFeatures * @param bbox [Optional] the spatial bounds to constrain the result set * @return * @throws Exception */ public WFSCountResponse getMiningActivityCount(String serviceURL, String mineName, String startDate, String endDate, String oreProcessed, String producedMaterial, String cutOffGrade, String production, int maxFeatures, FilterBoundingBox bbox ) throws Exception { //create the filter MiningActivityFilter filter = new MiningActivityFilter(mineName, startDate, endDate, oreProcessed, producedMaterial, cutOffGrade, production); String filterString = generateFilterString(filter, bbox); HttpMethodBase method = generateWFSRequest(serviceURL, MINING_ACTIVITY_FEATURE_TYPE, null, filterString, maxFeatures, null, ResultType.Hits); return getWfsFeatureCount(method); }
/** * Gets all RDF concepts at the specified repository as a single JENA Model. The results * will be requested page by page until the entire repository has been traversed. * * @return * @throws PortalServiceException */ public Model getAllCommodityConcepts() throws PortalServiceException { Model model = ModelFactory.createDefaultModel(); int pageNumber = 0; int pageSize = this.getPageSize(); //Request each page in turn - put the results into Model do { HttpMethodBase method = ((CommodityVocabMethodMaker)sissVocMethodMaker).getAllCommodities(getBaseUrl(), getRepository(), Format.Rdf, pageSize, pageNumber); if (requestPageOfConcepts(method, model)) { pageNumber++; } else { break; } } while (true); return model; }
/** * Will attempt to parse an <DataServiceError> element * * Will throw an PressureDBException if document does contain an <DataServiceError>, otherwise it will do nothing * @param doc * @throws PressureDBException */ public static void checkForExceptionResponse(Document doc) throws PortalServiceException { XPath xPath = XPathFactory.newInstance().newXPath(); try { //Check for an exception response NodeList exceptionNodes = (NodeList)xPath.evaluate("/DataServiceError", doc, XPathConstants.NODESET); if (exceptionNodes.getLength() > 0) { Node exceptionNode = exceptionNodes.item(0); throw new PortalServiceException((HttpMethodBase)null, exceptionNode.getTextContent()); } } catch (XPathExpressionException ex) { //This should *hopefully* never occur log.error("Error whilst attempting to check for errors", ex); } }
protected static HttpMethodBase buildHttpClientMethod(String url, String method) { if ("GET".equals(method)) { return new GetMethod(url); } if ("POST".equals(method)) { return new PostMethod(url); } if ("PUT".equals(method)) { return new PutMethod(url); } if ("DELETE".equals(method)) { return new DeleteMethod(url); } if (TestingMethod.METHOD_NAME.equals(method)) { return new TestingMethod(url); } throw new UnsupportedOperationException("Method '"+method+"' not supported"); }
protected static HttpMethodBase buildHttpClientMethod(String url, Class<? extends HttpMethodBase> method) { HttpMethodBase request = null; try { request = method.getConstructor(String.class).newInstance(url); } catch(Exception e) { throw new AlfrescoRuntimeException("HttpClient broken", e); } return request; }
/** * Will create the method and execute it. After this the method is sent to a * ResponseHandler that is returned. * * @param httpRequest * Request we are receiving from the client * @param url * The location we are proxying to * @return A ResponseHandler that can be used to write the response * @throws MethodNotAllowedException * If the method specified by the request isn't handled * @throws IOException * When there is a problem with the streams * @throws HttpException * The httpclient can throw HttpExcetion when executing the * method */ ResponseHandler executeRequest(HttpServletRequest httpRequest, String url) throws MethodNotAllowedException, IOException, HttpException { RequestHandler requestHandler = RequestHandlerFactory .createRequestMethod(httpRequest.getMethod()); HttpMethod method = requestHandler.process(httpRequest, url); method.setFollowRedirects(false); /* * Why does method.validate() return true when the method has been * aborted? I mean, if validate returns true the API says that means * that the method is ready to be executed. TODO I don't like doing type * casting here, see above. */ if (!((HttpMethodBase) method).isAborted()) { httpClient.executeMethod(method); if (method.getStatusCode() == 405) { Header allow = method.getResponseHeader("allow"); String value = allow.getValue(); throw new MethodNotAllowedException( "Status code 405 from server", AllowedMethodHandler.processAllowHeader(value)); } } return ResponseHandlerFactory.createResponseHandler(method); }
/** * Add the headers to the method, and the auth token (which must be set * @param method method to update * @param requestHeaders the list of headers * @throws SwiftInternalStateException not yet authenticated */ private void setHeaders(HttpMethodBase method, Header[] requestHeaders) throws SwiftInternalStateException { for (Header header : requestHeaders) { method.addRequestHeader(header); } setAuthToken(method, getToken()); }
private void runTest(HttpMethodBase m, int expectedStatus) throws Exception { m.setFollowRedirects(false); final int status = httpClient.executeMethod(m); assertEquals(expectedStatus, status); final String content = getResponseBodyAsStream(m, 0); final String scriptTag = "<script>"; assertFalse("Content should not contain '" + scriptTag + "'", content.contains(scriptTag)); }
/** * Builds a new Request object, using HttpClient method descriptions */ public RemoteConnectorRequest buildRequest(String url, Class<? extends HttpMethodBase> method) { // Get the method name String methodName; try { HttpMethodBase httpMethod = method.getConstructor(String.class).newInstance(url); methodName = httpMethod.getName(); } catch(Exception e) { throw new AlfrescoRuntimeException("Error identifying method name", e); } // Build and return return buildRequest(url, methodName); }
public String getResponse() { if (responseBytes != null) { if (method instanceof HttpMethodBase) { // mimic method.getResponseBodyAsString return EncodingUtil.getString(responseBytes, ((HttpMethodBase)method).getResponseCharSet()); } else { return new String(responseBytes); } } else { return null; } }
private static void copyHttpMethodBase( HttpMethodBase m, HttpMethodBase copy) { try { copy.setParams((HttpMethodParams)m.getParams().clone()); } catch (CloneNotSupportedException e) { // Should never happen } }
@SuppressWarnings("unused") private final void showHeaders(final HttpMethodBase methodBase) { final Header[] headers = methodBase.getResponseHeaders(); for (int i = 0; i < headers.length; i++) { System.out.println("header name: " + headers[i].getName()); System.out.println("header value: " + headers[i].getValue()); } }
private static byte[] executeMethod(HttpMethodBase method, int timeout) throws Exception { InputStream in = null; try { method.addRequestHeader("Connection", "close"); HttpClient client = new HttpClient(); HttpConnectionManagerParams params = client.getHttpConnectionManager().getParams(); //设置连接时候一些参数 params.setConnectionTimeout(timeout); params.setSoTimeout(timeout); params.setStaleCheckingEnabled(false); ByteArrayOutputStream baos = new ByteArrayOutputStream(BUFFER_SIZE); int stat = client.executeMethod(method); if (stat != HttpStatus.SC_OK) log.error("get失败!"); //method.getResponseBody() in = method.getResponseBodyAsStream(); byte[] buffer = new byte[BUFFER_SIZE]; int len; while ((len = in.read(buffer)) > 0) { baos.write(buffer, 0, len); } return baos.toByteArray(); } finally { if (in != null) { in.close(); } } }
/** * 执行HTTP GET/POST * @return 执行结果 * @throws IOException */ public HttpResponse execute() throws IOException { HttpClient httpClient = createHttpClient(); HttpMethodBase method = null; try { createProxy(httpClient); basicAuth(httpClient); method = createMethod(); // 放在try中,防止url有错误,异常抛出 return executeMethod(httpClient, method); } finally { shutdown(method); } }
private void shutdown(HttpMethodBase method) { if (method != null) { method.releaseConnection(); } if (!externalConnectionManager) { ((SimpleHttpConnectionManager) httpConnectionManager).shutdown(); } }
private HttpResponse executeMethod(HttpClient httpClient, HttpMethodBase method) throws IOException { int responseCode = httpClient.executeMethod(method); HttpResponse httpResponse = new HttpResponse(); httpResponse.setResponseCode(responseCode); httpResponse.setResponseContent(method.getResponseBodyAsStream()); httpResponse.setResponseCharSet(method.getResponseCharSet()); return httpResponse; }
/** * Calculate response headers size * * @return the size response headers (in bytes) */ private static int calculateHeadersSize(HttpMethodBase httpMethod) { int headerSize = httpMethod.getStatusLine().toString().length()+2; // add a \r\n Header[] rh = httpMethod.getResponseHeaders(); for (Header responseHeader : rh) { headerSize += responseHeader.toString().length(); // already include the \r\n } headerSize += 2; // last \r\n before response data return headerSize; }
/** * * 设置请求头方法 * * @author zcj * @param hmb GetMethod or PostMethod * @time 2016-10-13 09:51:18 * */ static void setHeader(HttpMethodBase hmb) { hmb.addRequestHeader("Cache-Control", "no-cache"); hmb.addRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"); hmb.addRequestHeader("Accept-Encoding", "gzip, deflate, sdch"); hmb.addRequestHeader("Accept-Language", "zh-CN,zh;q=0.8"); hmb.addRequestHeader("Cache-Control", "max-age=0"); hmb.addRequestHeader("Connection", "Keep-Alive"); hmb.addRequestHeader("Content-Type", "application/x-www-form-urlencoded"); hmb.addRequestHeader("Host", "kyfw.12306.cn"); hmb.addRequestHeader("Upgrade-Insecure-Requests", "1"); hmb.addRequestHeader("Referer", "https://kyfw.12306.cn/otn/login/init"); hmb.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"); }
private HttpMethodBase setHeader(HttpMethodBase method) { Map<String, List<String>> value = getNameValuePairs(header, "header"); if (value != null) { for (Map.Entry<String, List<String>> entry : value.entrySet()) { for (String v : entry.getValue()) { method.addRequestHeader(entry.getKey(), v); } } } else if (header != null) { throw new PaxmlRuntimeException("Header should be key-value pairs but got: " + header); } return method; }
private HttpMethodBase setQueryString(HttpMethodBase method) { Map<String, List<String>> value = getNameValuePairs(query, "query"); if (value != null) { List<NameValuePair> pairs = new ArrayList<NameValuePair>(); for (Map.Entry<String, List<String>> entry : value.entrySet()) { for (String v : entry.getValue()) { pairs.add(new NameValuePair(entry.getKey(), v)); } } method.setQueryString(pairs.toArray(new NameValuePair[pairs.size()])); } else if (query != null) { method.setQueryString(query.toString()); } return method; }
/** * Requests the received method with the received timeout (milliseconds). * * Executes the method through the inherited HttpClient.executedMethod(method). * * Sets the socket and connection timeouts only for the method received. * * The timeouts are both in milliseconds; 0 means 'infinite'; * < 0 means 'do not change the default' * * @param method HTTP method request. * @param readTimeout Timeout to set for data reception * @param connectionTimeout Timeout to set for connection establishment */ public int executeMethod(HttpMethodBase method, int readTimeout, int connectionTimeout) throws IOException { int oldSoTimeout = getParams().getSoTimeout(); int oldConnectionTimeout = getHttpConnectionManager().getParams().getConnectionTimeout(); try { if (readTimeout >= 0) { method.getParams().setSoTimeout(readTimeout); // this should be enough... getParams().setSoTimeout(readTimeout); // ... but HTTPS needs this } if (connectionTimeout >= 0) { getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout); } return executeMethod(method); } finally { getParams().setSoTimeout(oldSoTimeout); getHttpConnectionManager().getParams().setConnectionTimeout(oldConnectionTimeout); } }
/** * Create a Commons HttpMethodBase object for the given HTTP method and URI specification. * @param httpMethod the HTTP method * @param uri the URI * @return the Commons HttpMethodBase object */ protected HttpMethodBase createCommonsHttpMethod(HttpMethod httpMethod, String uri) { switch (httpMethod) { case GET: return new GetMethod(uri); case DELETE: return new DeleteMethod(uri); case HEAD: return new HeadMethod(uri); case OPTIONS: return new OptionsMethod(uri); case POST: return new PostMethod(uri); case PUT: return new PutMethod(uri); case TRACE: return new TraceMethod(uri); default: throw new IllegalArgumentException("Invalid HTTP method: " + httpMethod); } }
@Override public int executeMethod(HttpMethod method) { try { Field responseBody = HttpMethodBase.class.getDeclaredField("responseBody"); responseBody.setAccessible(true); responseBody.set(method, expectedResponseBody.getBytes()); } catch (Exception e) { throw new RuntimeException("Exception setting response stream", e); } return expectedResponseStatus; }