I want to construct a httprequest like below to access the rest webservice using post request. I have used spring for android API to generate the request. I am able to add header with httpHeader.add method but dont know add message to the body. The request format is as below.
<?xml version="1.0" encoding="UTF-8"?>
<root>
<headers>
<messagetype>1</messagetype>
<uniquekey>95C75718-C774-DF4E-0DB4-A7AEF55077AA</uniquekey>
</headers>
<authentication>
<clientname>xxx</clientname>
<servicename>login</servicename>
<username>xxx123</username>
<password>welcome123</password>
</authentication>
</root>
I dont how to add that part. Please Help.
The code i done so far is below
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
public class Main extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView webservice = (TextView) findViewById(R.id.Webservice);
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.TEXT_PLAIN);
requestHeaders.add("messagetype", "1");
requestHeaders.add("uniquekey", UniqueID.getUUID());
HttpEntity<String> requestEntity = new HttpEntity<String>(requestHeaders);
RestTemplate restTemplate = new RestTemplate();
String url = "http://www.localhost:8080/restwebservice/login";
ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
String result = responseEntity.getBody();
webservice.setText(result);
}
}
You need to create a
Messageobject and pass it to the RestTemplate. Check out section 2.6.5 of theRestTemplatedocumentation for specifics.Note that the example there is different from your approach and uses
postForObjectinstead ofexchange. If you still want to stay withexchange, you should change theHttpEntityyou are using forrequestEntityand use one that allows you to add the body of your message to it.BasicHttpEntityshould work just fine, although you will have to construct the XML in the body by hand. On the other hand,postForObjectwith the proper message formater will allow you to pass plain old Java object and get it properly serialized into XML automatically. There are many options for message formatters, but I would recommend Jackson as it is quite fast and well supported (even though it more known for its JSON support and less for XML).