我正在使用Java中的curl命令字符串发送POST请求。我在命令字符串中传递 json,该字符串的值中包含空格。当编译器遇到 json 中的空格时,我收到错误。我需要保留空格并传递字符串curl 命令中的值。请帮忙。如果有人可以重写我的 string[] 命令来帮助我理解我的错误,我会很棒。这是我的代码。
String[] command = { "curl", "-X", "POST", "http://my.url.com/add", "-H", "accept: application/json", "-H", "AuthorizationToken: 123", "-H", "Content-Type: application/json", "-d", "{\"FieldLabels\":\"Name,Status,Employee number\",\"FieldValues\":\"test7,Planned,Raj Kumar(123)\",\"Type\":\"BT\"}" };
ProcessBuilder process = new ProcessBuilder(command);
Process p;
try
{
p = process.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
builder.append(line);
builder.append(System.getProperty("line.separator"));
}
String result = builder.toString();
System.out.print(result);
}
catch (Exception e)
{
e.printStackTrace();
}
Error:
{
"message" : {
"statusCode" : "500",
"Status" : "Internal Server Error",
"requestedURI" : "/api/EFormService/createEFormItemData",
"error" : "Expected a ':' after a key at character 25 of {FieldLabels:Name,Status,Employee"
}
}
最佳答案
尝试将 json 请求放入文件中,并在curl 请求中使用以下格式
--data "@<path/to/file>"
'@'表示请求数据位于以下路径的文件中。
举个例子:
数据:
{"FieldLabels":"Name,Status,Employee number","FieldValues":"test7,Planned,Raj Kumar(123)","Type":"BT"}
此数据需要保存到文件中,例如:/tmp/reqData 那么下面是你的命令
{ "curl", "-X", "POST", "http://my.url.com/add", "-H", "accept: application/json", "-H", "AuthorizationToken: 123", "-H", "Content-Type: application/json", "-d", "@/tmp/reqData" };
关于java - 在Java中的curl命令字符串中传递Json值中的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61305689/