Post XML file to a page from Android

Working on one of my projects, I met a pretty simple task – post constructed XML file to certain page on a Web Server.

You will need to create additional class for this purpose SBGen.java:

public class SBGen {
	public String constructXml(Context context){
		//DATA
		StringBuilder sb = new StringBuilder();
        sb.append("");
        	sb.append("");
        sb.append("");
		
		return sb.toString();
	}
}

Then just add the following code to your Action:

String link = "http://ServerName/Post.php";
    	
    	HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(link);

        try {

        	SBGen XmlClass= new SBGen();
        	String xmlFile = XmlClass.constructXml(this);
            StringEntity entity = new StringEntity(xmlFile, "UTF-8");
            httppost.setEntity(entity);  
            httppost.addHeader("Accept", "application/xml");
            httppost.addHeader("Content-Type", "application/xml");

            HttpResponse response = httpclient.execute(httppost); 
            
            if (response.getStatusLine() != null) 
Toast.makeText(getParent(), response.getStatusLine(), Toast.LENGTH_SHORT).show();
           //You can get response from calling response.getEntity() and manipulate with it as you need.
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

4 comments

Leave a Reply

%d bloggers like this: