我尝试了多种方法从 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/