我有一个带有graphql api的nodejs后端。我想从我的Java应用程序向此api发送一个http请求。我发送请求的代码是:
String query = "query{ login( name: \"" + username + "\", password: \"" + password + "\" ) { token, userId, name }}";
String postEndpoint = "http://localhost:8000";
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(postEndpoint);
httpPost.setHeader("Content-Type", "application/json");
String inputJson = "{\n" +
" \"query\": \"" + query + "\"\n" +
"}";
System.out.println(inputJson);
StringEntity stringEntity = new StringEntity(inputJson);
httpPost.setEntity(stringEntity);
HttpResponse response = httpClient.execute(httpPost);
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent()))
);
if(response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " +
response.getStatusLine().getStatusCode());
}
StringBuffer result = new StringBuffer();
String line = "";
while((line = br.readLine()) != null) {
System.out.println("Response : \n"+result.append(line));
}
在插入变量username的位置,后端总是出现意外的字符错误。这个查询我在做什么错? 谢谢