Java Code Examples for org.apache.http.entity.BasicHttpEntity#setContent()

The following examples show how to use org.apache.http.entity.BasicHttpEntity#setContent() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ApacheHttpResponseBuilder.java    From junit-servers with MIT License 6 votes vote down vote up
@Override
public HttpResponse build() {
	ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
	StatusLine statusLine = new BasicStatusLine(protocolVersion, status, "");
	HttpResponse response = new BasicHttpResponse(statusLine);

	InputStream is = new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8));
	BasicHttpEntity entity = new BasicHttpEntity();
	entity.setContent(is);
	response.setEntity(entity);

	for (Map.Entry<String, List<String>> header : headers.entrySet()) {
		for (String value : header.getValue()) {
			response.addHeader(header.getKey(), value);
		}
	}

	return response;
}
 
Example 2
Source File: GenericApiGatewayClientTest.java    From apigateway-generic-java-sdk with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws IOException {
    AWSCredentialsProvider credentials = new AWSStaticCredentialsProvider(new BasicAWSCredentials("foo", "bar"));

    mockClient = Mockito.mock(SdkHttpClient.class);
    HttpResponse resp = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK"));
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(new ByteArrayInputStream("test payload".getBytes()));
    resp.setEntity(entity);
    Mockito.doReturn(resp).when(mockClient).execute(any(HttpUriRequest.class), any(HttpContext.class));

    ClientConfiguration clientConfig = new ClientConfiguration();

    client = new GenericApiGatewayClientBuilder()
            .withClientConfiguration(clientConfig)
            .withCredentials(credentials)
            .withEndpoint("https://foobar.execute-api.us-east-1.amazonaws.com")
            .withRegion(Region.getRegion(Regions.fromName("us-east-1")))
            .withApiKey("12345")
            .withHttpClient(new AmazonHttpClient(clientConfig, mockClient, null))
            .build();
}
 
Example 3
Source File: HurlStack.java    From barterli_android with Apache License 2.0 6 votes vote down vote up
/**
 * Initializes an {@link HttpEntity} from the given
 * {@link HttpURLConnection}.
 * 
 * @param connection
 * @return an HttpEntity populated with data from <code>connection</code>.
 */
private static HttpEntity entityFromConnection(HttpURLConnection connection) {

    BasicHttpEntity entity = new BasicHttpEntity();
    InputStream inputStream;
    try {
        inputStream = connection.getInputStream();
    } catch (IOException ioe) {
        inputStream = connection.getErrorStream();
    }
    entity.setContent(inputStream);
    entity.setContentLength(connection.getContentLength());
    entity.setContentEncoding(connection.getContentEncoding());
    entity.setContentType(connection.getContentType());
    return entity;
}
 
Example 4
Source File: HttpKnife.java    From WeGit with Apache License 2.0 6 votes vote down vote up
/**
 * 获取响应报文实体
 * 
 * @return
 * @throws IOException
 */
private HttpEntity entityFromConnection() throws IOException {
	BasicHttpEntity entity = new BasicHttpEntity();
	InputStream inputStream;
	try {
		inputStream = connection.getInputStream();
	} catch (IOException ioe) {
		inputStream = connection.getErrorStream();
	}
	if (GZIP.equals(getResponseheader(ResponseHeader.HEADER_CONTENT_ENCODING))) {
		entity.setContent(new GZIPInputStream(inputStream));
	} else {
		entity.setContent(inputStream);
	}
	entity.setContentLength(connection.getContentLength());
	entity.setContentEncoding(connection.getContentEncoding());
	entity.setContentType(connection.getContentType());
	return entity;
}
 
Example 5
Source File: StoryWebServiceControllerTest.java    From ezScrum with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testAddExistedTask() throws Exception {
	// create 3 tasks in project
	TaskObject task1 = new TaskObject(mProject.getId());
	task1.setName("TASK_NAME1").save();
	
	TaskObject task2 = new TaskObject(mProject.getId());
	task2.setName("TASK_NAME2").save();
	
	TaskObject task3 = new TaskObject(mProject.getId());
	task3.setName("TASK_NAME3").save();
	
	// initial request data,add task#1 & #3 to story#1
	StoryObject story = mASTS.getStories().get(0);
	String taskIdJsonString = String.format("[%s, %s]", task1.getId(), task2.getId());
	String URL = String.format(API_URL, mProjectName, story.getId() + "/add-existed-task", mUsername, mPassword);
	BasicHttpEntity entity = new BasicHttpEntity();
	entity.setContent(new ByteArrayInputStream(taskIdJsonString.getBytes()));
	entity.setContentEncoding("utf-8");
	HttpPost httpPost = new HttpPost(URL);
	httpPost.setEntity(entity);
	mHttpClient.execute(httpPost);
	
	story.reload();
	assertEquals(2, story.getTasks().size());
}
 
Example 6
Source File: HurlStack.java    From device-database with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes an {@link HttpEntity} from the given {@link HttpURLConnection}.
 * @param connection
 * @return an HttpEntity populated with data from <code>connection</code>.
 */
private static HttpEntity entityFromConnection(HttpURLConnection connection) {
    BasicHttpEntity entity = new BasicHttpEntity();
    InputStream inputStream;
    try {
        inputStream = connection.getInputStream();
    } catch (IOException ioe) {
        inputStream = connection.getErrorStream();
    }
    entity.setContent(inputStream);
    entity.setContentLength(connection.getContentLength());
    entity.setContentEncoding(connection.getContentEncoding());
    entity.setContentType(connection.getContentType());
    return entity;
}
 
Example 7
Source File: OkHttpStack.java    From SimplifyReader with Apache License 2.0 5 votes vote down vote up
private static HttpEntity entityFromOkHttpResponse(Response r) throws IOException {
    BasicHttpEntity entity = new BasicHttpEntity();
    ResponseBody body = r.body();

    entity.setContent(body.byteStream());
    entity.setContentLength(body.contentLength());
    entity.setContentEncoding(r.header("Content-Encoding"));

    if (body.contentType() != null) {
        entity.setContentType(body.contentType().type());
    }
    return entity;
}
 
Example 8
Source File: OkHttpURLConnectionStack.java    From AndroidProjects with MIT License 5 votes vote down vote up
private static HttpEntity entityFromOkHttpResponse(Response r) throws IOException {
    BasicHttpEntity entity = new BasicHttpEntity();
    ResponseBody body = r.body();

    entity.setContent(body.byteStream());
    entity.setContentLength(body.contentLength());
    entity.setContentEncoding(r.header("Content-Encoding"));

    if (body.contentType() != null) {
        entity.setContentType(body.contentType().type());
    }
    return entity;
}
 
Example 9
Source File: HurlStack.java    From jus with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes an {@link HttpEntity} from the given {@link HttpURLConnection}.
 * @param connection
 * @return an HttpEntity populated with data from <code>connection</code>.
 */
private static HttpEntity entityFromConnection(HttpURLConnection connection) {
    BasicHttpEntity entity = new BasicHttpEntity();
    InputStream inputStream;
    try {
        inputStream = connection.getInputStream();
    } catch (IOException ioe) {
        inputStream = connection.getErrorStream();
    }
    entity.setContent(inputStream);
    entity.setContentLength(connection.getContentLength());
    entity.setContentEncoding(connection.getContentEncoding());
    entity.setContentType(connection.getContentType());
    return entity;
}
 
Example 10
Source File: StoryApiTest.java    From ezScrum with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testPost() throws Exception {
	// 預設已經新增五個 stories
	ArrayList<StoryObject> stories = mProject.getStories();
	assertEquals(5, stories.size());

	// initial request data
	JSONObject storyJson = new JSONObject();
	storyJson.put("name", "TEST_NAME").put("notes", "TEST_NOTES")
			.put("how_to_demo", "TEST_HOW_TO_DEMO").put("importance", 99)
			.put("value", 15).put("estimate", 21).put("status", 0)
			.put("sprint_id", -1).put("tags", "")
			.put("project_name", mProject.getName());

	BasicHttpEntity entity = new BasicHttpEntity();
	entity.setContent(new ByteArrayInputStream(storyJson.toString()
			.getBytes()));
	entity.setContentEncoding("utf-8");
	HttpPost httpPost = new HttpPost(API_URL);
	httpPost.setEntity(entity);
	setHeaders(httpPost, mAccountId, mPlatformType);
	HttpResponse httpResponse = mClient.execute(httpPost);
	String result = EntityUtils.toString(httpResponse.getEntity());
	JSONObject response = new JSONObject(result);

	// 新增一個 story,project 內的 story 要有六個
	stories = mProject.getStories();
	assertEquals(6, stories.size());
	// 對回傳的 JSON 做 assert
	assertEquals("SUCCESS", response.getString("status"));
	assertEquals(stories.get(stories.size() - 1).getId(),
			response.getLong("storyId"));
}
 
Example 11
Source File: OkHttpStack.java    From openshop.io-android with MIT License 5 votes vote down vote up
private static HttpEntity entityFromOkHttpResponse(Response r) throws IOException {
    BasicHttpEntity entity = new BasicHttpEntity();
    ResponseBody body = r.body();

    entity.setContent(body.byteStream());
    entity.setContentLength(body.contentLength());
    entity.setContentEncoding(r.header("Content-Encoding"));

    if (body.contentType() != null) {
        entity.setContentType(body.contentType().type());
    }
    return entity;
}
 
Example 12
Source File: HurlStack.java    From FeedListViewDemo with MIT License 5 votes vote down vote up
/**
 * Initializes an {@link HttpEntity} from the given {@link HttpURLConnection}.
 * @param connection
 * @return an HttpEntity populated with data from <code>connection</code>.
 */
private static HttpEntity entityFromConnection(HttpURLConnection connection) {
    BasicHttpEntity entity = new BasicHttpEntity();
    InputStream inputStream;
    try {
        inputStream = connection.getInputStream();
    } catch (IOException ioe) {
        inputStream = connection.getErrorStream();
    }
    entity.setContent(inputStream);
    entity.setContentLength(connection.getContentLength());
    entity.setContentEncoding(connection.getContentEncoding());
    entity.setContentType(connection.getContentType());
    return entity;
}
 
Example 13
Source File: AuthenticationHandlerTest.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
private CloseableHttpResponse getAccessTokenReponse() throws IOException {
    CloseableHttpResponse mockDCRResponse = new MockHttpResponse();
    String dcrResponseFile = TestUtils.getAbsolutePathOfConfig("accesstoken-response.json");
    BasicHttpEntity responseEntity = new BasicHttpEntity();
    responseEntity.setContent(new ByteArrayInputStream(getContent(dcrResponseFile).
            getBytes(StandardCharsets.UTF_8.name())));
    responseEntity.setContentType(TestUtils.CONTENT_TYPE);
    mockDCRResponse.setEntity(responseEntity);
    mockDCRResponse.setStatusLine(new BasicStatusLine(new ProtocolVersion("http", 1, 0), 200, "OK"));
    return mockDCRResponse;
}
 
Example 14
Source File: AuthenticationHandlerTest.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
private CloseableHttpResponse getInvalidResponse() throws UnsupportedEncodingException {
    CloseableHttpResponse mockDCRResponse = new MockHttpResponse();
    BasicHttpEntity responseEntity = new BasicHttpEntity();
    responseEntity.setContent(new ByteArrayInputStream("invalid response".getBytes(StandardCharsets.UTF_8.name())));
    responseEntity.setContentType(TestUtils.CONTENT_TYPE);
    mockDCRResponse.setEntity(responseEntity);
    mockDCRResponse.setStatusLine(new BasicStatusLine(new ProtocolVersion("http", 1, 0), 400, "Bad Request"));
    return mockDCRResponse;
}
 
Example 15
Source File: MockCatalogService.java    From azure-devops-intellij with MIT License 5 votes vote down vote up
public void addResponse(String response) throws HttpException {
    final HttpResponse httpResponse = new BasicHttpResponse(
            new BasicStatusLine(new ProtocolVersion("https", 1, 0), HttpStatus.SC_OK, "reason"));
    final BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(new ByteArrayInputStream(response.getBytes()));
    httpResponse.setEntity(entity);
    responses.add(httpResponse);
}
 
Example 16
Source File: TestInvokeAmazonGatewayApiMock.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Test
public void testSendAttributes() throws Exception {

    HttpResponse resp = new BasicHttpResponse(
        new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK"));
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(new ByteArrayInputStream("test payload".getBytes()));
    resp.setEntity(entity);
    Mockito.doReturn(resp).when(mockSdkClient)
           .execute(any(HttpUriRequest.class), any(HttpContext.class));

    // add dynamic property
    runner.setProperty("dynamicHeader", "yes!");
    // set the regex
    runner.setProperty(InvokeAWSGatewayApi.PROP_ATTRIBUTES_TO_SEND, "F.*");

    final Map<String, String> attributes = new HashMap<>();
    attributes.put(CoreAttributes.MIME_TYPE.key(), "application/plain-text");
    attributes.put("Foo", "Bar");
    runner.enqueue("Hello".getBytes("UTF-8"), attributes);
    // execute
    runner.assertValid();
    runner.run(1);

    Mockito.verify(mockSdkClient, times(1))
            .execute(argThat(argument -> argument.getMethod().equals("GET")
                            && argument.getFirstHeader("x-api-key").getValue().equals("abcd")
                            && argument.getFirstHeader("Authorization").getValue().startsWith("AWS4")
                            && argument.getFirstHeader("dynamicHeader").getValue().equals("yes!")
                            && argument.getFirstHeader("Foo").getValue().equals("Bar")
                            && argument.getURI().toString().equals("https://foobar.execute-api.us-east-1.amazonaws.com/TEST")),
                    any(HttpContext.class));
    // check
    runner.assertTransferCount(InvokeAWSGatewayApi.REL_SUCCESS_REQ, 1);
    runner.assertTransferCount(InvokeAWSGatewayApi.REL_RESPONSE, 1);
    runner.assertTransferCount(InvokeAWSGatewayApi.REL_RETRY, 0);
    runner.assertTransferCount(InvokeAWSGatewayApi.REL_NO_RETRY, 0);
    runner.assertTransferCount(InvokeAWSGatewayApi.REL_FAILURE, 0);

    final List<MockFlowFile> flowFiles = runner
        .getFlowFilesForRelationship(InvokeAWSGatewayApi.REL_RESPONSE);
    final MockFlowFile ff0 = flowFiles.get(0);

    ff0.assertAttributeEquals(InvokeAWSGatewayApi.STATUS_CODE, "200");
    ff0.assertContentEquals("test payload");
    ff0.assertAttributeExists(InvokeAWSGatewayApi.TRANSACTION_ID);
    ff0.assertAttributeEquals(InvokeAWSGatewayApi.RESOURCE_NAME_ATTR, "/TEST");
}
 
Example 17
Source File: MockServer.java    From aws-sdk-java-v2 with Apache License 2.0 4 votes vote down vote up
private static void setEntity(HttpResponse response, String content) {
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(new StringInputStream(content));
    response.setEntity(entity);
}
 
Example 18
Source File: Sample.java    From aws-request-signing-apache-interceptor with Apache License 2.0 4 votes vote down vote up
HttpEntity stringEntity(final String body) throws UnsupportedEncodingException {
    BasicHttpEntity httpEntity = new BasicHttpEntity();
    httpEntity.setContent(new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8.name())));
    return httpEntity;
}
 
Example 19
Source File: SprintPlanWebServiceControllerTest.java    From ezScrum with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void testUpdateSprint() throws Exception {
	// Test Data
	int interval = 2;
	int members = 4;
	int availableHours = 80;
	int focusFactor = 90;
	String sprintGoal = "TEST_SPRINT_GOAL_NEW";
	String startDate = "2013/07/01";
	String demoDate = "2013/07/22";
	String demoPlace = "TEST_DEMO_PLACE";
	String dailyInfo = "TEST_DAILY_INFO_NEW";
	String dueDate = "2013/07/22";

	SprintObject updateSpint = mCS.getSprints().get(0);
	// prepare request data
	JSONObject sprintJson = new JSONObject();
	sprintJson.put(SprintEnum.ID, updateSpint.getId())
	        .put(SprintEnum.INTERVAL, interval)
	        .put(SprintEnum.TEAM_SIZE, members)
	        .put(SprintEnum.AVAILABLE_HOURS, availableHours)
	        .put(SprintEnum.FOCUS_FACTOR, focusFactor)
	        .put(SprintEnum.GOAL, sprintGoal)
	        .put(SprintEnum.START_DATE, startDate)
	        .put(SprintEnum.DEMO_DATE, demoDate)
	        .put(SprintEnum.DEMO_PLACE, demoPlace)
	        .put(SprintEnum.DAILY_INFO, dailyInfo)
	        .put(SprintEnum.DUE_DATE, dueDate);

	// Assemble URL
	String URL = String.format(API_URL, mProjectName, "update", mUsername, mPassword);

	// Send Http Request
	BasicHttpEntity entity = new BasicHttpEntity();
	entity.setContent(new ByteArrayInputStream(sprintJson.toString().getBytes()));
	entity.setContentEncoding(StandardCharsets.UTF_8.name());
	HttpPut httpPut = new HttpPut(URL);
	httpPut.setEntity(entity);
	EntityUtils.toString(mHttpClient.execute(httpPut).getEntity(), StandardCharsets.UTF_8);

	// get Sprint
	SprintObject sprint = SprintObject.get(updateSpint.getId());

	// assert
	assertEquals(interval, sprint.getInterval());
	assertEquals(members, sprint.getTeamSize());
	assertEquals(availableHours, sprint.getAvailableHours());
	assertEquals(focusFactor, sprint.getFocusFactor());
	assertEquals(sprintGoal, sprint.getGoal());
	assertEquals(startDate, sprint.getStartDateString());
	assertEquals(demoDate, sprint.getDemoDateString());
	assertEquals(demoPlace, sprint.getDemoPlace());
	assertEquals(dailyInfo, sprint.getDailyInfo());
}
 
Example 20
Source File: Entities.java    From RoboZombie with Apache License 2.0 4 votes vote down vote up
/**
 * <p>Discovers which implementation of {@link HttpEntity} is suitable for wrapping the given object. 
 * This discovery proceeds in the following order by checking the runtime-type of the object:</p> 
 *
 * <ol>
 * 	<li>org.apache.http.{@link HttpEntity} --&gt; returned as-is.</li> 
 * 	<li>{@code byte[]}, {@link Byte}[] --&gt; {@link ByteArrayEntity}</li> 
 *  	<li>java.io.{@link File} --&gt; {@link FileEntity}</li>
 * 	<li>java.io.{@link InputStream} --&gt; {@link BufferedHttpEntity}</li>
 * 	<li>{@link CharSequence} --&gt; {@link StringEntity}</li>
 * 	<li>java.io.{@link Serializable} --&gt; {@link SerializableEntity} (with an internal buffer)</li>
 * </ol>
 *
 * @param genericEntity
 * 			a generic reference to an object whose concrete {@link HttpEntity} is to be resolved 
 * <br><br>
 * @return the resolved concrete {@link HttpEntity} implementation
 * <br><br>
 * @throws NullPointerException
 * 			if the supplied generic type was {@code null}
 * <br><br>
 * @throws EntityResolutionFailedException
 * 			if the given generic instance failed to be translated to an {@link HttpEntity} 
 * <br><br>
 * @since 1.3.0
 */
public static final HttpEntity resolve(Object genericEntity) {

 assertNotNull(genericEntity);

 try {

	 if(genericEntity instanceof HttpEntity) {
		
		 return (HttpEntity)genericEntity;
	 }
	 else if(byte[].class.isAssignableFrom(genericEntity.getClass())) {
		
		 return new ByteArrayEntity((byte[])genericEntity);
	 }
	 else if(Byte[].class.isAssignableFrom(genericEntity.getClass())) {
		
		 Byte[] wrapperBytes = (Byte[])genericEntity;
		 byte[] primitiveBytes = new byte[wrapperBytes.length];
		
		 for (int i = 0; i < wrapperBytes.length; i++) {
			
			 primitiveBytes[i] = wrapperBytes[i].byteValue();
		 }
		
		 return new ByteArrayEntity(primitiveBytes);
	 }
	 else if(genericEntity instanceof File) {
		
		 return new FileEntity((File)genericEntity, null);
	 }
	 else if(genericEntity instanceof InputStream) {
		
		 BasicHttpEntity basicHttpEntity = new BasicHttpEntity();
		 basicHttpEntity.setContent((InputStream)genericEntity);
		
		 return new BufferedHttpEntity(basicHttpEntity);
	 }
	 else if(genericEntity instanceof CharSequence) {
		
		 return new StringEntity(((CharSequence)genericEntity).toString());
	 }
	 else if(genericEntity instanceof Serializable) {
		
		 return new SerializableEntity((Serializable)genericEntity, true);
	 }
	 else {
		
		 throw new EntityResolutionFailedException(genericEntity);
	 }
 }
 catch(Exception e) {

	 throw (e instanceof EntityResolutionFailedException)?
			 (EntityResolutionFailedException)e :new EntityResolutionFailedException(genericEntity, e);
 }
}