我见过几个人拿一个字符串并将其用作 Json 的例子。我想从一个包含 json 的文件中读取,并将其用作我的请求的正文。最有效的方法是什么?
非常感谢帮忙。我的最终解决方案,使用 groovy 控制台并从 .json 文件中读取,如下所示:
@Grab(group='org.apache.httpcomponents', module='httpclient', version='4.2.3')
@Grab(group='org.apache.httpcomponents', module='httpcore', version='4.2.3')
@Grab(group='org.apache.commons', module='commons-io', version='1.3.2')
import org.apache.http.impl.client.DefaultHttpClient
import org.apache.http.client.methods.HttpPost
import org.apache.http.HttpResponse
import org.apache.http.HttpEntity
import org.apache.http.entity.StringEntity
import org.apache.http.util.EntityUtils
import org.apache.commons.io.IOUtils
String json = IOUtils.toString(new FileInputStream("C:\\MyHome\\example.json"));
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://api/location/send");
httpPost.addHeader("content-type", "application/json");
httpPost.setEntity(new StringEntity(json));
HttpResponse response2 = httpclient.execute(httpPost);
try {
System.out.println(response2.getStatusLine());
HttpEntity entity2 = response2.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(entity2);
} finally {
httpPost.releaseConnection();
}
这对我来说是一个很好的快速健全性检查,是一种快速原型化的好方法,可以更好地了解我正在尝试做的事情。再次感谢。