Hi,
I am having Restful webservice and Android client for Restful Webservice in Java. I sucessfully coded to get the respose using HttpGet() method. but i coudnt how to Post using HttpPost() to Restful Service from Android.
Here are my Webservice:
package com.myeclipseide.ws;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import com.sun.jersey.spi.resource.Singleton;
@Produces("application/xml")
@Path("customers")
@Singleton
public class CustomerResource {
private TreeMap<Integer, Customer> customerMap = new TreeMap<Integer, Customer>();
public CustomerResource() {
// hardcode a single customer into the database for demonstration
// purposes
Customer customer = new Customer();
customer.setName("Harold Abernathy");
customer.setAddress("Sheffield, UK");
addCustomer(customer);
}
@GET
public List<Customer> getCustomers() {
List<Customer> customers = new ArrayList<Customer>();
customers.addAll(customerMap.values());
return customers;
}
@GET
@Path("{id}")
public Customer getCustomer(@PathParam("id") int cId) {
return customerMap.get(cId);
}
@POST
@Path("add")
@Produces("text/plain")
@Consumes("application/xml")
public String addCustomer(Customer customer) {
int id = customerMap.size();
customer.setId(id);
customerMap.put(id, customer);
return "Customer " + customer.getName() + " added with Id " + id;
}
}
My Android Code
I dont know how to give the URL for Post Method in HttpPost()
public
void post1()
{
// String xml = "<customer><address>1223</address><name>niwin</name></customer>";
String xml =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+
"<customers><customer><address>Sheffield, UK</address>"
+
"<id>0</id><name>Harold Abernathy</name></customer></customers>";
StringEntity se = null;
HttpPost postRequest = new HttpPost("http://192.168.2.23:1234/RestfulWS/services/customers/add");
try {
se = new StringEntity(xml,HTTP.UTF_8);
se.setContentType("text/xml");
postRequest.setHeader("Content-Type","application/soap+xml;charset=UTF-8");
postRequest.setEntity(se);
HttpClient httpclient = new DefaultHttpClient();
//HttpResponse resp=httpclient.execute(postRequest);
BasicHttpResponse httpResponse;
try {
httpResponse = (BasicHttpResponse) httpclient.execute(postRequest);
Log.d("HTTPStatus",httpResponse.getStatusLine().toString());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
Log.d(
"UnsupportedEncodingException ","Resp:\n"+e.getMessage());
e.printStackTrace();
}
The above programs execute with error free but i am not getting the Posted values in Webservice
Please Help me how to overcome this one?