In the last post we saw how to do a get request using HttpClient in android. Now lets see how to do a post request, wherein we send some data to the server and then read the response.
The below code uses the HttpResponseContainerVO object from the previous post to retrieve the data.
public static HttpResponseContainerVO getPostResponse(String url,
final byte[] data)
throws IOException {
HttpResponseContainerVO responseVo = new HttpResponseContainerVO();
HttpPost post = new HttpPost(url);
// Add the headers
post.addHeader(new BasicHeader("Accept","application/json"));
post.setEntity(new HttpEntity() {
@Override
public void writeTo(OutputStream outstream) throws IOException {
outstream.write(data);
}
@Override
public boolean isStreaming() {
return false;
}
@Override
public boolean isRepeatable() {
return false;
}
@Override
public boolean isChunked() {
return false;
}
@Override
public Header getContentType() {
return new BasicHeader("Content-Type","application/json");
}
@Override
public long getContentLength() {
return data.length;
}
@Override
public Header getContentEncoding() {
return null;
}
@Override
public InputStream getContent() throws IOException,
IllegalStateException {
InputStream is = new ByteArrayInputStream(data, 0, data.length);
return is;
}
@Override
public void consumeContent() throws IOException {
}
});
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
ByteArrayOutputStream content = new ByteArrayOutputStream();
responseVo.setResponseCode(response.getStatusLine().getStatusCode());
Header[] headers = response.getAllHeaders();
for (Header hdr : headers) {
//Store the required headers
}
// Read response into a buffered stream
int readBytes = 0;
byte[] sBuffer = new byte[512];
while ((readBytes = inputStream.read(sBuffer)) != -1) {
content.write(sBuffer, 0, readBytes);
}
responseVo.setResponse(new String(content.toByteArray()));
return responseVo;
That's all :)
No comments:
Post a Comment