样例Spring RestTemplate实现

时间:2018-09-17 07:39:04

标签: spring spring-boot github resttemplate

我想从我的本地spring应用程序中将一些存档文件推送到GITHub中。

repos/{:user}/{:repo}/git/refs/heads/{:branchname}

{
    SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
    Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("XXXXXX", 8080));
    requestFactory.setProxy(proxy);
    RestTemplate restTemplate = new RestTemplate(requestFactory);
    String url = new String("https://api.github.com/repos/XXX/MyApplication/git/refs/heads/XXX");
    Map<String, String> req = new HashMap<String,String>();
    req.put("sha", "9a7fd370e28ea7a4bc8242e7f234s5ed07042cb88");
    String jsonObject = JSONParser.quote(payload);
    HttpEntity<Object> httpEntity = new HttpEntity<>(headers1);
   restTemplate.exchange(url, HttpMethod.POST,httpEntity,Object.class);
}

Error: Exception in thread "main" org.springframework.web.client.HttpClientErrorException: 404 Not Found
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:63)
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:700)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:653)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:613)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:531)

使用下面的POST API,我收到“ 404 not found错误”。

Method : POST
URL : https://api.github.com/repos/{:user}/{:repo}/git/refs/heads/{:branchname}
{
  "sha": "{:new-commit-sha}"
}

您能为上述api提供示例Spring RestTemplate实现吗?

1 个答案:

答案 0 :(得分:1)

我在上述情况下发现了问题。为此,标题中的POST客户端userId和密码是错误的。

我们需要在BasicAutherizationInceptors类中提供userId和Password,如下所示。

resttemplate.getInterceptors().add(new BasicAutherizationInterceptor(userId,Pwd));