服务器端为spring mvc,使用@RequestBody自动接收请求数据并转换为bean。
public class Wrapper {
public VOBean data;
public VOBean getData() {
return data;
}
public void setData(VOBean data) {
this.data = data;
}
}
客户端使用apache的httpclient。
import java.io.IOException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
public class PostClient {
public static void main(String[] args) throws IOException {
String url = "http://xxxx";
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(url);
method.setRequestHeader("Context-Type", "application/json; charset=utf-8");
method.setRequestHeader("Accept", "application/json; charset=utf-8");
VoBean avo= new VoBean();// set bean params
net.sf.json.JSONObject jo = net.sf.json.JSONObject.fromObject(avo);
String avoJson = "{\"data\":"+jo.toString()+"}";
method.setRequestEntity(new StringRequestEntity(avoJson, "application/json", "utf-8"));
try {
client.executeMethod(method);
String resp = "";
if (method.getStatusCode() == HttpStatus.SC_OK)
resp = method.getResponseBodyAsString();
System.out.println(resp);
} finally {
method.releaseConnection();
}
}
}