下面列出了org.apache.http.nio.IOControl#org.apache.http.entity.BasicHttpEntity 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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();
}
@Test
public void testExecute_non2xx_exception() throws IOException {
HttpResponse resp = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, 404, "Not found"));
BasicHttpEntity entity = new BasicHttpEntity();
entity.setContent(new ByteArrayInputStream("{\"message\" : \"error payload\"}".getBytes()));
resp.setEntity(entity);
Mockito.doReturn(resp).when(mockClient).execute(any(HttpUriRequest.class), any(HttpContext.class));
Map<String, String> headers = new HashMap<>();
headers.put("Account-Id", "fubar");
headers.put("Content-Type", "application/json");
try {
client.execute(
new GenericApiGatewayRequestBuilder()
.withBody(new ByteArrayInputStream("test request".getBytes()))
.withHttpMethod(HttpMethodName.POST)
.withHeaders(headers)
.withResourcePath("/test/orders").build());
Assert.fail("Expected exception");
} catch (GenericApiGatewayException e) {
assertEquals("Wrong status code", 404, e.getStatusCode());
assertEquals("Wrong exception message", "{\"message\":\"error payload\"}", e.getErrorMessage());
}
}
public HttpResponse getHttpResponse(final String path) throws IOException {
try (CloseableHttpResponse closeableHttpResponse = super.get(path)) {
HttpEntity entity = closeableHttpResponse.getEntity();
BasicHttpEntity basicHttpEntity = new BasicHttpEntity();
String content = EntityUtils.toString(entity);
basicHttpEntity.setContent(IOUtils.toInputStream(content));
basicHttpEntity.setContentEncoding(entity.getContentEncoding());
basicHttpEntity.setContentLength(entity.getContentLength());
basicHttpEntity.setContentType(entity.getContentType());
basicHttpEntity.setChunked(entity.isChunked());
StatusLine statusLine = closeableHttpResponse.getStatusLine();
HttpResponse response = new BasicHttpResponse(statusLine);
response.setEntity(basicHttpEntity);
response.setHeaders(closeableHttpResponse.getAllHeaders());
response.setLocale(closeableHttpResponse.getLocale());
return response;
}
}
public static String postBody(String url, String body, Map<String, String> headers, int timeout) throws Exception {
HttpClient client = buildHttpClient(url);
HttpPost httppost = new HttpPost(url);
httppost.setHeader("charset", "utf-8");
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout)
.setConnectionRequestTimeout(timeout).setStaleConnectionCheckEnabled(true).build();
httppost.setConfig(requestConfig);
buildHeader(headers, httppost);
BasicHttpEntity requestBody = new BasicHttpEntity();
requestBody.setContent(new ByteArrayInputStream(body.getBytes("UTF-8")));
requestBody.setContentLength(body.getBytes("UTF-8").length);
httppost.setEntity(requestBody);
// 执行客户端请求
HttpResponse response = client.execute(httppost);
HttpEntity entity = response.getEntity();
return EntityUtils.toString(entity, "UTF-8");
}
public static byte[] getPostContent(HttpRequest request) {
if (!(request instanceof HttpEntityEnclosingRequest)) {
LOGGER.warning("Unknown request type for POST request " + request.getClass());
return null;
}
HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request;
HttpEntity entity = entityRequest.getEntity();
if (!(entity instanceof BasicHttpEntity)) {
LOGGER.warning("Unknown entity type for POST request " + entity.getClass());
return null;
}
BasicHttpEntity basicEntity = (BasicHttpEntity) entity;
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
try {
basicEntity.writeTo(buffer);
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to read all request content.", e);
return null;
}
return buffer.toByteArray();
}
@Before
public void initExecutor() throws IOException {
CloseableHttpClient httpMock = mock(CloseableHttpClient.class);
when(httpMock.execute(any())).thenAnswer(invocationOnMock -> {
HttpGet get = (HttpGet) invocationOnMock.getArguments()[0];
mockLog.append(get.getMethod()).append(" ").append(get.getURI()).append(" ");
switch (mockReturnCode) {
case FAIL_RETURN_CODE: throw new RuntimeException("FAIL");
case TIMEOUT_RETURN_CODE: throw new SocketTimeoutException("read timed out");
}
BasicStatusLine statusLine = new BasicStatusLine(HttpVersion.HTTP_1_1, mockReturnCode, null);
BasicHttpEntity entity = new BasicHttpEntity();
String returnMessage = "{\"foo\":\"bar\", \"no\":3, \"error-code\": " + mockReturnCode + "}";
InputStream stream = new ByteArrayInputStream(returnMessage.getBytes(StandardCharsets.UTF_8));
entity.setContent(stream);
CloseableHttpResponse response = mock(CloseableHttpResponse.class);
when(response.getEntity()).thenReturn(entity);
when(response.getStatusLine()).thenReturn(statusLine);
return response;
});
configServerApi = ConfigServerApiImpl.createForTestingWithClient(configServers, httpMock);
}
/**
* Initializes an {@link HttpEntity} from the given {@link HttpURLConnection}.
*
* @return an HttpEntity populated with data from <code>connection</code>.
*/
/*
* 通过一个 HttpURLConnection 获取其对应的 HttpEntity ( 这里就 HttpEntity 而言,耦合了 Apache )
*/
private static HttpEntity entityFromConnection(HttpURLConnection connection) {
BasicHttpEntity entity = new BasicHttpEntity();
InputStream inputStream;
try {
inputStream = connection.getInputStream();
} catch (IOException ioe) {
inputStream = connection.getErrorStream();
}
// 设置 HttpEntity 的内容
entity.setContent(inputStream);
// 设置 HttpEntity 的长度
entity.setContentLength(connection.getContentLength());
// 设置 HttpEntity 的编码
entity.setContentEncoding(connection.getContentEncoding());
// 设置 HttpEntity Content-Type
entity.setContentType(connection.getContentType());
return entity;
}
private CloseableHttpResponse getValidationResponse() throws UnsupportedEncodingException {
ValidationResponce response = new ValidationResponce();
response.setDeviceId("1234");
response.setDeviceType("testdevice");
response.setJWTToken("1234567788888888");
response.setTenantId(-1234);
Gson gson = new Gson();
String jsonReponse = gson.toJson(response);
CloseableHttpResponse mockDCRResponse = new MockHttpResponse();
BasicHttpEntity responseEntity = new BasicHttpEntity();
responseEntity.setContent(new ByteArrayInputStream(jsonReponse.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;
}
private CloseableHttpResponse doWithEntity(Body body, CloseableHttpClient httpClient, HttpUriRequest request) throws IOException {
if (!(request instanceof HttpEntityEnclosingRequestBase)) {
throw new IllegalArgumentException("Expecting to write an body for a request type that does not support it!");
}
PipedOutputStream pipedOutputStream = buildPipedOutputStream();
PipedInputStream pipedInputStream = buildPipedInputStream();
pipedInputStream.connect(pipedOutputStream);
BasicHttpEntity httpEntity = new BasicHttpEntity();
httpEntity.setContent(pipedInputStream);
((HttpEntityEnclosingRequestBase) request).setEntity(httpEntity);
writeEntityOutOverConnection(body, pipedOutputStream);
return doExecute(httpClient, request);
}
/**
* 获取响应报文实体
*
* @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;
}
@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());
}
/**
* 执行HTTP请求之后获取到其数据流,即返回请求结果的流
*
* @param connection
* @return
*/
private HttpEntity entityFromURLConnwction(HttpURLConnection connection) {
BasicHttpEntity entity = new BasicHttpEntity();
InputStream inputStream = null;
try {
inputStream = connection.getInputStream();
} catch (IOException e) {
e.printStackTrace();
inputStream = connection.getErrorStream();
}
// TODO : GZIP
entity.setContent(inputStream);
entity.setContentLength(connection.getContentLength());
entity.setContentEncoding(connection.getContentEncoding());
entity.setContentType(connection.getContentType());
return entity;
}
/**
* 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;
}
/**
* 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;
}
@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;
}
public AsyncWrappedOutputStream(Message message,
boolean needToCacheRequest,
boolean isChunking,
int chunkThreshold,
String conduitName,
URI uri) {
super(message,
needToCacheRequest,
isChunking,
chunkThreshold,
conduitName,
uri);
csPolicy = getClient(message);
entity = message.get(CXFHttpRequest.class);
basicEntity = (BasicHttpEntity)entity.getEntity();
basicEntity.setChunked(isChunking);
HeapByteBufferAllocator allocator = new HeapByteBufferAllocator();
int bufSize = csPolicy.getChunkLength() > 0 ? csPolicy.getChunkLength() : 16320;
inbuf = new SharedInputBuffer(bufSize, allocator);
outbuf = new SharedOutputBuffer(bufSize, allocator);
isAsync = outMessage != null && outMessage.getExchange() != null
&& !outMessage.getExchange().isSynchronous();
}
@Test
public void shouldDownloadArtifact() throws IOException, URISyntaxException {
String url = "http://blah";
FetchHandler fetchHandler = mock(FetchHandler.class);
HttpGet mockGetMethod = mock(HttpGet.class);
CloseableHttpResponse response = mock(CloseableHttpResponse.class);
BasicHttpEntity basicHttpEntity = new BasicHttpEntity();
ByteArrayInputStream instream = new ByteArrayInputStream(new byte[]{});
basicHttpEntity.setContent(instream);
when(response.getEntity()).thenReturn(basicHttpEntity);
when(response.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK"));
when(httpClient.execute(mockGetMethod)).thenReturn(response);
when(httpClientFactory.createGet(url)).thenReturn(mockGetMethod);
when(mockGetMethod.getURI()).thenReturn(new URI(url));
service.download(url, fetchHandler);
verify(httpClient).execute(mockGetMethod);
verify(fetchHandler).handle(instream);
}
HttpPost createPost(DeployRequest deployRequest, String host) {
URI deployUri = createDeployUri(host, deployRequest.getEndpoint());
log.info("Deploying to host : " + deployUri.toString());
HttpPost post = new HttpPost(deployUri);
if (!StringUtils.isNullOrEmpty(authToken)) {
log.info("Adding authToken to request header.");
post.addHeader("authToken", authToken);
}
ByteArrayInputStream bos = new ByteArrayInputStream(deployRequest.toJson(false).getBytes());
BasicHttpEntity entity = new BasicHttpEntity();
entity.setContent(bos);
entity.setContentLength(deployRequest.toJson(false).getBytes().length);
post.setEntity(entity);
return post;
}
/**
* <p>Test for a {@link Request} with a <b>buffered</b> entity.</p>
*
* @since 1.3.0
*/
@Test
public final void testBufferedHttpEntity() throws ParseException, IOException {
Robolectric.getFakeHttpLayer().interceptHttpRequests(false);
String subpath = "/bufferedhttpentity";
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream inputStream = classLoader.getResourceAsStream("LICENSE.txt");
InputStream parallelInputStream = classLoader.getResourceAsStream("LICENSE.txt");
BasicHttpEntity bhe = new BasicHttpEntity();
bhe.setContent(parallelInputStream);
stubFor(put(urlEqualTo(subpath))
.willReturn(aResponse()
.withStatus(200)));
requestEndpoint.bufferedHttpEntity(inputStream);
verify(putRequestedFor(urlEqualTo(subpath))
.withRequestBody(equalTo(EntityUtils.toString(new BufferedHttpEntity(bhe)))));
}
@Before
public void setup() throws Exception {
HttpClientManager.HttpClientBuilderFacade builder = mock( HttpClientManager.HttpClientBuilderFacade.class );
HttpClientManager manager = mock( HttpClientManager.class );
doReturn( builder ).when( manager ).createBuilder();
CloseableHttpClient client = mock( CloseableHttpClient.class );
doReturn( client ).when( builder ).build();
CloseableHttpResponse response = mock( CloseableHttpResponse.class );
doReturn( response ).when( client ).execute( any( HttpGet.class ) );
BasicHttpEntity entity = new BasicHttpEntity();
entity.setContent( new ByteArrayInputStream( DATA.getBytes() ) );
doReturn( entity ).when( response ).getEntity();
mockStatic( HttpClientManager.class );
when( HttpClientManager.getInstance() ).thenReturn( manager );
setInternalState( data, "realUrl", "http://project-hop.org" );
setInternalState( data, "argnrs", new int[ 0 ] );
doReturn( false ).when( meta ).isUrlInField();
doReturn( "body" ).when( meta ).getFieldName();
doReturn( false ).when( log ).isDetailed();
doCallRealMethod().when( http ).callHttpService( any( IRowMeta.class ), any( Object[].class ) );
doReturn( HttpURLConnection.HTTP_OK ).when( http ).requestStatusCode( any( CloseableHttpResponse.class ) );
doReturn( new Header[ 0 ] ).when( http ).searchForHeaders( any( CloseableHttpResponse.class ) );
setInternalState( http, "log", log );
setInternalState( http, "data", data );
setInternalState( http, "meta", meta );
}
/**
* @deprecated use {@link #executeRequest} instead to avoid a dependency on the deprecated
* Apache HTTP library. Nothing in Volley's own source calls this method. However, since
* {@link BasicNetwork#mHttpStack} is exposed to subclasses, we provide this implementation
* in case legacy client apps are dependent on that field. This method may be removed in a
* future release of Volley.
*/
@Deprecated
@Override
public final org.apache.http.HttpResponse performRequest(
Request<?> request, Map<String, String> additionalHeaders)
throws IOException, AuthFailureError {
HttpResponse response = executeRequest(request, additionalHeaders);
ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
StatusLine statusLine =
new BasicStatusLine(
protocolVersion, response.getStatusCode(), /* reasonPhrase= */ "");
BasicHttpResponse apacheResponse = new BasicHttpResponse(statusLine);
List<org.apache.http.Header> headers = new ArrayList<>();
for (Header header : response.getHeaders()) {
headers.add(new BasicHeader(header.getName(), header.getValue()));
}
apacheResponse.setHeaders(headers.toArray(new org.apache.http.Header[0]));
InputStream responseStream = response.getContent();
if (responseStream != null) {
BasicHttpEntity entity = new BasicHttpEntity();
entity.setContent(responseStream);
entity.setContentLength(response.getContentLength());
apacheResponse.setEntity(entity);
}
return apacheResponse;
}
@Test
public void testCreateStory() throws Exception {
// 預設已經新增五個 stories
ArrayList<StoryObject> stories = mProject.getStories();
assertEquals(mStoryCount, 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", "");
String URL = String.format(API_URL, mProjectName, "create", mUsername, mPassword);
BasicHttpEntity entity = new BasicHttpEntity();
entity.setContent(new ByteArrayInputStream(storyJson.toString().getBytes()));
entity.setContentEncoding("utf-8");
HttpPost httpPost = new HttpPost(URL);
httpPost.setEntity(entity);
String result = EntityUtils.toString(mHttpClient.execute(httpPost).getEntity(), StandardCharsets.UTF_8);
JSONObject response = new JSONObject(result);
// 新增一個 story,project 內的 story 要有六個
stories = mProject.getStories();
assertEquals(mStoryCount + 1, stories.size());
// 對回傳的 JSON 做 assert
assertEquals("SUCCESS", response.getString("status"));
assertEquals(stories.get(stories.size()-1).getId(), response.getLong("storyId"));
}
@Override
public boolean validate() throws ConfigurationException {
try {
if (Strings.isNullOrEmpty(packageName.getText())) {
Messages.showErrorDialog("顶层包名不能为空", "错误提示");
return false;
}
if (Strings.isNullOrEmpty(groupId.getText())) {
Messages.showErrorDialog("项目组织名不能为空", "错误提示");
return false;
}
if (Strings.isNullOrEmpty(artifactId.getText())) {
Messages.showErrorDialog("项目ID不能为空", "错误提示");
return false;
}
if (Strings.isNullOrEmpty(finalName.getText())) {
Messages.showErrorDialog("发布文件名不能为空", "错误提示");
return false;
}
BasicHttpEntity entity = new BasicHttpEntity();
entity.setContent(new ByteArrayInputStream(gson.toJson(getPostData()).getBytes()));
String json = HttpUtil.post(makerUrl.getText() + "/maker/make", entity);
HashMap redata = gson.fromJson(json, HashMap.class);
boolean ok = Boolean.parseBoolean(String.valueOf(redata.getOrDefault("ok", "false")));
if (ok) {
downLoadKey = String.valueOf(redata.get("key"));
moduleBuilder.setModuleName(finalName.getText());
return true;
} else {
downLoadKey = null;
Messages.showErrorDialog(redata.getOrDefault("msg", "服务暂不可用!请稍后再试!").toString(), "错误提示");
return false;
}
} catch (Exception e) {
throw new ConfigurationException("构筑中心发生未知异常! " + e.getMessage());
}
}
@Override
public void receiveResponseEntity(final HttpResponse response) throws HttpException, IOException {
_logFunc.log("receive response body start", "receiveResponseBodyStart");
super.receiveResponseEntity(response);
HttpEntity entity = response.getEntity();
if (entity != null && entity.getContent() != null) {
((BasicHttpEntity) entity).setContent(new TracingInputStream(entity.getContent(), _logFunc));
}
}
private static void setEntity(HttpResponse response, String content) {
try {
BasicHttpEntity entity = new BasicHttpEntity();
entity.setContent(new StringInputStream(content));
response.setEntity(entity);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
private BasicHttpResponse createBasicHttpResponse() {
BasicHttpEntity entity = new BasicHttpEntity();
entity.setContent(new ByteArrayInputStream(new byte[0]));
BasicHttpResponse response = new BasicHttpResponse(
new ProtocolVersion("http", 1, 1),
200,
"OK");
response.setEntity(entity);
return response;
}
private static HttpEntity getEntity(Response response) throws IOException {
BasicHttpEntity entity = new BasicHttpEntity();
ResponseBody body = response.body();
entity.setContent(body.byteStream());
entity.setContentLength(body.contentLength());
entity.setContentEncoding(response.header("Content-Encoding"));
if (body.contentType() != null) {
entity.setContentType(body.contentType().type());
}
return entity;
}
private static BasicHttpEntity httpEntityWithJsonPayload(Object payload) {
String jsonPayload = toJsonString(payload);
BasicHttpEntity entity = new BasicHttpEntity();
entity.setContent(new ByteArrayInputStream(jsonPayload.getBytes(UTF_8)));
return entity;
}
/**
* 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;
}
private void writeResponse(final HttpResponse resp, final String responseText, final int statusCode, final String responseType, final String reasonPhrase) {
try {
resp.setStatusCode(statusCode);
resp.setReasonPhrase(reasonPhrase);
final BasicHttpEntity body = new BasicHttpEntity();
if (HttpUtils.RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) {
// JSON response
body.setContentType(getJSONContentType());
if (responseText == null) {
body.setContent(new ByteArrayInputStream("{ \"error\" : { \"description\" : \"Internal Server Error\" } }".getBytes(HttpUtils.UTF_8)));
}
} else {
body.setContentType("text/xml");
if (responseText == null) {
body.setContent(new ByteArrayInputStream("<error>Internal Server Error</error>".getBytes(HttpUtils.UTF_8)));
}
}
if (responseText != null) {
body.setContent(new ByteArrayInputStream(responseText.getBytes(HttpUtils.UTF_8)));
}
resp.setEntity(body);
} catch (final Exception ex) {
s_logger.error("error!", ex);
}
}