Talking To Web Servers Via HTTP In Android 1.0

Read Time:50 Second
HttpClient httpClient = new DefaultHttpClient();
StringBuilder uriBuilder = new StringBuilder(SERVICE_ENDPOINT);
uriBuilder.append("?param0=" + param0);
uriBuilder.append("&param1=" + param1);
uriBuilder.append("&paramN=" + paramN);
HttpGet request = new HttpGet(uriBuilder.toString());
HttpResponse response = httpClient.execute(request);
int status = response.getStatusLine().getStatusCode();
// we assume that the response body contains the error message
if (status != HttpStatus.SC_OK) {
ByteArrayOutputStream ostream = new ByteArrayOutputStream();
response.getEntity().writeTo(ostream);
Log.e("HTTP CLIENT", ostream.toString()));
} else {
InputStream content = response.getEntity().getContent();
// <consume response>
content.close(); // this will also close the connection
}
------
HttpClient httpClient = new DefaultHttpClient();
HttpPost request = new HttpPost(SERVICE_ENDPOINT);
MultipartEntity entity = new MultipartEntity();
entity.addPart("param0", new StringBody("value0"));
entity.addPart("param1", new StringBody(Double.toString(1.0)));
entity.addPart("paramN", new FileBody(new File("/bar/baz")));
request.setEntity(entity);
HttpResponse response = httpClient.execute(request);
int status = response.getStatusLine().getStatusCode();
if (status != HttpStatus.SC_OK) {
// see above
} else {
// see above
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.