2010-03-02

How to send a XML web request and get the response in an Android application

// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
your_url_here
);
HttpResponse response = null;
InputStream content = null;

try {
    // Add your data
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("data",
your_xml_request_here));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    // Execute HTTP Post Request
    response = httpclient.execute(httppost);
    content = response.getEntity().getContent();

    BufferedReader rd = new BufferedReader(new InputStreamReader(content), 4096);
    String line;
    StringBuilder sb = new StringBuilder();
    while ((line = rd.readLine()) != null) {
        sb.append(line);
    }
    rd.close();
    strResponse = sb.toString();

} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
} catch (IOException e) {
    // TODO Auto-generated catch block
}

No comments: