java - 如何调用带有多个参数的spring API?

标签 java spring spring-mvc spring-boot

我尝试了多种方法从 spring Controller 调用 spring API,但我无法成功。有人可以给我一些关于如何像这样向 API 发布值的线索吗?

@POST
@Path("/referencesfromconverter/update/{referenceType}/{jsonOutput}")
public void saveReferences(@PathParam("referenceType") String referenceType, 
                           @PathParam("jsonOutput") String jsonOutput)

我的代码调用 API,但它不起作用。

public static void sendPostReferences(String referenceType,String jsonOutput) throws Exception
{
    List<NameValuePair> params=new ArrayList<>();
    String       postUrl       = "http://localhost:8181/EngineServer/rest/converterbuilder/json/referencesfromconverter/update";
    HttpClient   httpClient    = HttpClientBuilder.create().build();
    HttpPost     post          = new HttpPost(postUrl);

    params.add(new BasicNameValuePair(referenceType,jsonOutput));
    try{
        post.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));
        post.setHeader("Content-type", "application/json");

        String authString = "admin" + ":" + "admin";
        System.out.println("auth string: " + authString);

        byte[] authEncBytes = Base64.getEncoder().encode(authString.getBytes());
        String authStringEnc = new String(authEncBytes);
        System.out.println("Base64 encoded auth string: " + authStringEnc);
        post.setHeader("Authorization", "Basic " + authStringEnc);
        HttpResponse response=httpClient.execute(post);
        log.info(String.valueOf(response.getStatusLine().getStatusCode()));
        log.info(String.valueOf(response.getStatusLine().getReasonPhrase()));
    }catch(Exception ex){
        ex.printStackTrace();
    }

最佳答案

由于您已经在使用 Spring,我建议使用 UriComponentsBuilder 构建 URL:

URI postUrl = UriComponentsBuilder
    .fromUriString("http://localhost:8181/EngineServer/rest/converterbuilder/json")
    .path("/referencesfromconverter/update/{referenceType}/{jsonOutput}")
    .buildAndExpand(referenceType, jsonOutput)
    .encode()
    .toUri();

然后将其作为参数传递给 HttpPost 构造函数。

关于java - 如何调用带有多个参数的spring API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49939559/

相关文章:

spring - Websockets - Tomcat+Spring+ActiveMQ 与 ActiveMQ 本身

java - 将tensorflow keras LSTM模型转换为.tflite或任何工作格式

Java:Windows 上的 Runtime.exec() 和 Unicode 符号:如何使其能够处理非英文字母?

Javac 未与 openjdk-6-jdk 一起安装

java - 来自 2 个包的 @ComponentScan

java - Spring HandlerMethodSelector.selectMethods 的替代品

java - 任务需要哪种结构?

java - Spring Boot 1.4.3 和 @ControllerAdvice

spring-mvc - Swagger - 默认情况下,Springfox 总是会生成一些响应消息 (401,403...)。我怎样才能删除它们?

java - 有没有办法在 Controller 级别 @PreAuthorize 注释中访问 PathVariable?