Post Json 例子 Spring Rest Template & HttpClient

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 entity = new HttpEntity(objectToString(form), headers);

String target = "http://localhost:8080/speed/user/register";
RestTemplate temp = new RestTemplate();
ResponseEntity 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;
}
}
}

你可能感兴趣的:(Code,Snippet)