标签: resttemplate

将授权的curl -u post请求与JSON数据转换为RestTemplate等效项

我正在使用 github api 使用curl 命令创建存储库,如下所示,它工作正常。

curl -i -u "username:password" -d '{ "name": "TestSystem", "auto_init": true, "private": true, "gitignore_template": "nanoc" }' https://github.host.com/api/v3/orgs/Tester/repos
Run Code Online (Sandbox Code Playgroud)

现在我需要执行上面相同的 url,HttpClient并且我正在我的项目中使用RestTemplate

我以前工作过RestTemplate,我知道如何执行简单的 url,但不知道如何使用RestTemplate-将上述 JSON 数据发布到我的 url

RestTemplate restTemplate = new RestTemplate();

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);

// Create a multimap to hold the named parameters
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<String, String>();
parameters.add("username", username);
parameters.add("password", password);

// Create the http entity for the request
HttpEntity<MultiValueMap<String, String>> entity =
            new …
Run Code Online (Sandbox Code Playgroud)

java git post curl resttemplate

1
推荐指数
1
解决办法
3159
查看次数

Spring REST 模板 - 401 未经授权的错误

我在 Spring Boot 应用程序中使用 Spring Rest 模板。

即使我传递了凭据,我总是收到 401 未经授权的错误。

我可以通过 Chrome REST Web 服务客户端访问此服务。

有没有一种简化的方法来访问SpringBoot中的REST模板。

下面是迄今为止导致 401 错误的代码片段

 private DetailsBean invokeDetailsRestService(UserParam userParam){
    ResponseEntity<DetailsBean> responseEntity = null;
    String url = "https://dev.com/app/identifyuser/";
    RestClientConfig restClientConfig =new RestClientConfig("user123","pass123");
    responseEntity= restClientConfig.postForEntity(url, userParam, DetailsBean.class);
    log.debug("User Details : {} ", responseEntity.getBody());
    return responseEntity.getBody();
}

public ClientHttpRequestFactory getRequestFactory(String userName,String password){
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials( new AuthScope(null, -1), new UsernamePasswordCredentials(userName,password) );
    HttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    return new HttpComponentsClientHttpRequestFactory(httpClient);
}
Run Code Online (Sandbox Code Playgroud)

RestClientConfig 类

  public RestClientConfig(String username, String password) …
Run Code Online (Sandbox Code Playgroud)

spring resttemplate spring-boot spring-rest

1
推荐指数
1
解决办法
3万
查看次数

如何修改java Rest模板客户端中的部分Content-Disposition

我正在努力使用 java spring 创建对某些内部服务的有效请求。问题在于多部分/表单数据边界的正确有效负载。

环境:java服务器->(其余)http multipart/form-data->一些服务

(中间没有浏览器)

有效负载应如下所示:

------WebKitFormBoundaryp8mrQWOb5GiyC90y
内容处置:表单数据;名称=“文件”;文件名=“0000.png”
内容类型:图像/png

[二进制数据]

------WebKitFormBoundaryp8mrQWOb5GiyC90y--

不幸的是,我无法更改此“标头”,并且我收到如下信息:

--fkGT7CJaQB9-2aa8G1ePv17iHKnWSsd
内容处置:表单数据;名称=“文件”
内容长度:170096

[二进制数据]

--fkGT7CJaQB9-2aa8G1ePv17iHKnWSsd--

我搜索了很多 stackoverlow 问题,但似乎没有任何效果。这就是我到目前为止所做的(生成上述有效负载):

HashMap<String, List<String>> additionalHeaders = new HashMap<>();
String fileMd5 = "tgrlfG0pjblWZB6g1f7j5w=="; //@todo
File file = new File(systemFile.getAbsoluteFileLocation());
Path filePath = Paths.get(systemFile.getAbsoluteFileLocation());
try{
    DiskFileItem fileItem = new DiskFileItem("file", "image/png", false, file.getName(), (int) file.length() , file.getParentFile());
    InputStream input =  new FileInputStream(file);
    OutputStream os = fileItem.getOutputStream();
    int ret = input.read();
    while ( ret != -1 )
    {
        os.write(ret);
        ret = input.read();
    } …
Run Code Online (Sandbox Code Playgroud)

java upload spring multipartform-data resttemplate

1
推荐指数
1
解决办法
3560
查看次数

Spring Boot - MVC - RestTemplate:在哪里为 MVC 应用程序初始化 RestTemplate 以使用远程 RESTful 服务

我将开发一个简单的 Spring MVC Web 应用程序,它将使用 Heroku 上的远程 RESTful 服务。

我希望 MVC Web 应用程序根据控制器调用 REST 服务。例如

  • localhost:8080/items打电话http://{REMOTE_SERVER}/api/items
  • localhost:8080/users打电话http://{REMOTE_SERVER}/api/users

等等等等

我按照 Spring 的官方 Spring Boot 文档“使用 Spring MVC 提供 Web 内容”来创建一个 Hello World 应用程序,并GreetingController举例说明。我想利用Spring的RestTemplate来调用REST服务。

我的应用程序类:

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(Application.class, args);

        System.out.println("Let's inspect the beans provided by Spring Boot:");

    }
}
Run Code Online (Sandbox Code Playgroud)

我的问候控制器:

@Controller
public class GreetingController {
    @GetMapping("/greeting")
    public String greeting(@RequestParam(name = "name", required …
Run Code Online (Sandbox Code Playgroud)

java spring spring-mvc resttemplate spring-boot

1
推荐指数
1
解决办法
6288
查看次数

Java“空指针异常”-responseEntity.getBody().isNull()

    ResponseEntity<JsonNode> response = null;

    //Calling POST Method
    response=restTemplate.exchange(url, HttpMethod.POST,request,JsonNode.class);
    restResponse.setStatusCode(response.getStatusCode());
    restResponse.setHeaders(response.getHeaders());
    if(response.getBody().isNull())
    {
        //DO SOMETHING
    }
Run Code Online (Sandbox Code Playgroud)

问题:面临空指针异常

尽管我尝试使用 check 处理 Not Null 场景response.getBody().isNull(),但似乎此检查也会导致空指针异常。

我的假设:response.getBody()应该返回我尝试执行isNull()方法的 JsonNode 对象。我不确定这个调用如何再次导致空指针异常。在 Intellij 上,它显示getBody()方法有@Nullable可能出现空指针异常。

我在网上搜索了一些解决方案,说使用response.getBody()!=null会起作用。我很困惑。那么方法有什么用呢isNull()

java resttemplate

1
推荐指数
1
解决办法
7558
查看次数

使用 Spring Boot 和 Eureka Server 时如何修复错误 java.net.UnknownHostException?

我有一个名为“documents-microservice”的 Spring Boot 微服务,它在 Eureka Server 中注册。我尝试使用 URL 中的名称和 with 来访问此微服务RestTemplate,如下所示:

ResponseEntity<String> response =    restTemplate.exchange("http://documents-microservice/document-name", HttpMethod.POST, entity, String.class);
Run Code Online (Sandbox Code Playgroud)

尽管我确信该服务名称在运行在端口 8761 上的 Eureka Server 上可用(见下图),但我仍然收到以下错误:

尤里卡服务器运行

错误:

org.springframework.web.client.ResourceAccessException: I/O error on POST request for "http://documents-microservice/document-name": documents-microservice; nested exception is java.net.UnknownHostException: documents-microservice
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:674)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:621)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:539)
    at ae.gov.adm.saeed.web.controller.util.CircularsControllerUtil.circularListView(CircularsControllerUtil.java:196)
    at ae.gov.adm.saeed.web.controller.CircularsController.viewCircularList(CircularsController.java:58)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) …
Run Code Online (Sandbox Code Playgroud)

java post resttemplate spring-boot netflix-eureka

1
推荐指数
1
解决办法
2万
查看次数

实现ClientHttpRequestInterceptor时修改Response Body

我面临以下问题:

我正在使用一个简单的方法调用另一个服务org.springframework.web.client.RestTemplate

调用它时,我需要拦截请求,修改请求正文,并让它继续流程。到目前为止,我没有遇到任何问题,因为org.springframework.http.client.ClientHttpRequestInterceptor我可以对我的请求执行任何我想要的操作(在将其发送到我正在调用的服务之前将 RequestObjectA 转换为 requestObjectB)。

问题:如何修改响应体?

我看到调用时ClientHttpResponse execute = clientHttpRequestExecution.execute(httpRequest, body)我可以让身体做execute.getBody(),所以我可以修改它,但我没有找到一种方法以某种方式将其设置回来。

有什么办法可以将我修改后的身体设置为ClientHttpResponse

java spring-mvc resttemplate spring-resttemplate

1
推荐指数
1
解决办法
4423
查看次数

休息模板。如何增加最大tcp连接数?

我有 RestTemplate:

@Bean(name = "restTemplateBean")
public RestTemplate restTemplate(RestTemplateBuilder builder) {
    return builder
            .interceptors(new HttpRequestInterceptor())
            .uriTemplateHandler(new DefaultUriBuilderFactory((host + ":" + port)))
            .build();
}
Run Code Online (Sandbox Code Playgroud)

当我多次调用 RestTemplate(例如 post 请求)时,它最多会创建 5 ~ 10 个 TCP 连接。如何增加 RestTemplate 创建的最大连接数?

java spring connection-pooling resttemplate

1
推荐指数
1
解决办法
3193
查看次数

Spring RestTemplate抛出IllegalArgumentException:不是有效的HTTP URL

java.lang.IllegalArgumentException:[https:// localhost/pcap/search?stime = 20110930%2E000000&etime = 20110930%2E235959&bpf = tcp

这是我使用Spring RestFul模板进行的调用:

final PcapSearchResponse pcapSearchResult = restTemplate.postForObject(
    nPulseApiUris.get(2), null, PcapSearchResponse.class, sTime, eTime, bpf);
Run Code Online (Sandbox Code Playgroud)

我不明白为什么这是一个糟糕的URL?我用UTF-8编码"." 字符,但我不知道为什么我的网址仍然无效.

非常感谢您的帮助!

谢谢您的帮助!!!

java rest spring spring-mvc resttemplate

0
推荐指数
1
解决办法
4132
查看次数

Jackson,将字符串反序列化为日期

我具有以下JSON属性:

"created_at":"2017-12-08T10:56:01.000Z"
Run Code Online (Sandbox Code Playgroud)

我想使用Jackson以下属性反序列化JSON文档:

@JsonProperty("created_at")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-ddTHH:mm:ss.SSSZ")
private java.util.Date createdAt;
Run Code Online (Sandbox Code Playgroud)

但失败,但以下异常:

org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [class com.example.domain.Product] and content type [application/json;charset=utf-8]
    at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:119)
    at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:986)
    at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:969)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:717)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:671)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:587)
Run Code Online (Sandbox Code Playgroud)

我在做什么错以及如何解决?

json jackson resttemplate

0
推荐指数
1
解决办法
762
查看次数