您的位置:首页 > 理论基础 > 计算机网络

Post Json 例子 Spring Rest Template & HttpClient

2014-03-13 12:04 981 查看
package com.lee;

import static java.lang.System.out;

import java.io.Serializable;

import java.io.StringWriter;

import org.apache.http.Consts;

import org.apache.http.HttpResponse;

import org.apache.http.client.HttpClient;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.entity.ContentType;

import org.apache.http.entity.StringEntity;

import org.apache.http.impl.client.HttpClients;

import org.apache.http.util.EntityUtils;

import org.codehaus.jackson.map.ObjectMapper;

import org.springframework.http.HttpEntity;

import org.springframework.http.HttpHeaders;

import org.springframework.http.MediaType;

import org.springframework.http.ResponseEntity;

import org.springframework.web.client.RestTemplate;

public class RestClientTest {

public static void main(String[] args) throws Exception {

register();

register2();

}

private static void register() throws Exception {

RegisterForm form = new RegisterForm();

form.setId("googleId");

form.setMarket("G");



HttpHeaders headers = new HttpHeaders();

headers.setContentType(MediaType.APPLICATION_JSON);



HttpEntity<String> entity = new HttpEntity<String>(objectToString(form), headers);

String target = "http://localhost:8080/speed/user/register";

RestTemplate temp = new RestTemplate();

ResponseEntity<String> output = temp.postForEntity(target, entity, String.class);

out.println("output ==>" + output);

out.println("output body==>" + output.getBody());

}

private static void register2() throws Exception {

RegisterForm form = new RegisterForm();

form.setId("googleId");

form.setMarket("G");



HttpClient client = HttpClients.createDefault();

HttpPost post = new HttpPost("http://localhost:8080/speed/user/register");

org.apache.http.HttpEntity entity = new StringEntity(JsonUtils.objectToString(form), ContentType.APPLICATION_JSON);



post.setEntity(entity);

HttpResponse response = client.execute(post);

org.apache.http.HttpEntity output = response.getEntity();



out.println("status is " + response.getStatusLine());

out.println("output ==>" + EntityUtils.toString(output, Consts.UTF_8));

}

private static String objectToString(Object obj) throws Exception {

ObjectMapper mapper = new ObjectMapper();

StringWriter writer = new StringWriter();



mapper.writeValue(writer, obj);

return writer.toString();

}

private static class RegisterForm implements Serializable {

/**

*

*/

private static final long serialVersionUID = 1056274847217485228L;

private String id;

private String market;

public String getId() {

return id;

}

public void setId(String id) {

this.id = id;

}

public String getMarket() {

return market;

}

public void setMarket(String market) {

this.market = market;

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: