我尝试了几种方法从spring控制器调用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();
}
答案 0 :(得分:1)
由于您已经在使用Spring,我建议您使用UriComponentsBuilder
构建网址:
URI postUrl = UriComponentsBuilder
.fromUriString("http://localhost:8181/EngineServer/rest/converterbuilder/json")
.path("/referencesfromconverter/update/{referenceType}/{jsonOutput}")
.buildAndExpand(referenceType, jsonOutput)
.encode()
.toUri();
然后将其作为参数传递给HttpPost
构造函数。
答案 1 :(得分:0)
我看到了你的问题。使用params.add会产生这样的url: / referencesfromconverter /更新?引用类型= jsonOutput
你必须用url汇总你的参数。 杜是这样的:
String url = "/referencesfromconverter/update/" + referenceType + "/" + jsonOutput;