[英]How can we call the spring API with multiple parameters?
I tried several ways to call the spring API from spring controller but I could not make it. 我尝试了几种从spring控制器调用spring API的方法,但我做不到。 Can someone please give me some clue on how to post value to the API like this?
有人可以给我一些有关如何向这样的API发布价值的线索吗?
@POST
@Path("/referencesfromconverter/update/{referenceType}/{jsonOutput}")
public void saveReferences(@PathParam("referenceType") String referenceType,
@PathParam("jsonOutput") String jsonOutput)
My code to call the API but it is not working. 我的代码调用了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();
}
Since you are already using Spring, I would recommend to build URL using UriComponentsBuilder
: 由于您已经在使用Spring,因此建议您使用
UriComponentsBuilder
构建URL:
URI postUrl = UriComponentsBuilder
.fromUriString("http://localhost:8181/EngineServer/rest/converterbuilder/json")
.path("/referencesfromconverter/update/{referenceType}/{jsonOutput}")
.buildAndExpand(referenceType, jsonOutput)
.encode()
.toUri();
And then pass it as parameter to HttpPost
constructor. 然后将其作为参数传递给
HttpPost
构造函数。
I see your problem. 我明白你的问题。 Use params.add will produce url like this : /referencesfromconverter/update?referenceType=jsonOutput
使用params.add将产生如下网址:/ referencesfromconverter / update?referenceType = jsonOutput
You must concat your params with url. 您必须使用url连接参数。 Du something like this :
杜这样的事情:
String url = "/referencesfromconverter/update/" + referenceType + "/" + jsonOutput;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.