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<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;
}
}
}
Spring框架中,可以使用RestTemplate类来发起REST请求,如果需要通过代理服务器访问MS Graph API,你需要将代理设置应用到RestTemplate实例上。以下是设置过程: 1. **使用application.properties配置** 在你的Spring Boot项目的`application.properties`或`application.yml`文件中,添加如下的proxy配置: ```properties spring: http: client: default-proxy: host: your-proxy-host port: your-proxy-port scheme: http username: (如果有认证) password: (如果有认证) ``` 确保将`your-proxy-host`、`your-proxy-port`替换为你的代理的实际地址和端口。 2. **手动创建RestTemplate实例** 创建一个自定义的RestTemplate实例,并传递代理配置: ```java @Autowired private ClientHttpRequestFactory requestFactory; RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(requestFactory)); // 设置代理 HttpComponentsClientHttpRequestFactory factory = (HttpComponentsClientHttpRequestFactory) requestFactory; factory.setProxy(new HttpHost(proxyHost, proxyPort, "http")); if (username != null && password != null) { UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password); factory.getHttpClient().setDefaultCredentialsProvider(new BasicCredentialsProvider().setCredentials(AuthScope.ANY, credentials)); } // 现在你可以使用restTemplate发请求了,例如: String response = restTemplate.getForObject(MS_GRAPH_API_URL, String.class); ``` 3. **使用RestTemplateBuilder工厂方法** 如果你在特定上下文中想要创建一个临时的RestTemplate实例,可以使用`RestTemplateBuilder`: ```java RestTemplate restTemplate = RestTemplateBuilder .withBasicAuthentication(username, password) .withUriTemplateHandler(new SimpleUriTemplateHandler()) .build(); restTemplate.setRequestFactory(requestFactory.setProxy(new HttpHost(proxyHost, proxyPort, "http"))); // 发起请求... ``` 4. **注意安全性和认证** 如果代理需要身份验证,上述代码已经包含了基本认证部分。如果MS Graph API还要求其他类型的认证,可能需要额外处理。 **相关问题--:** 1. 如何检查RestTemplate是否成功设置了代理? 2. 如果MS Graph API返回407错误,怎么解决? 3. 如果代理只在某些条件下才启用,如何动态调整RestTemplate的代理设置?
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值