我想构建一个像下面这样的 httprequest 来使用 post 请求访问其余的 web 服务。我已经使用 spring for android API 来生成请求。我可以使用 httpHeader.add 方法添加标题,但不知道将消息添加到正文。请求格式如下。
<?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>
我不知道如何添加那部分。请帮忙。
我到目前为止完成的代码如下
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);
}
}