我见过几个人拿字符串并将其用作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();
}
这对我来说是一个非常快速的理智检查,这是一个快速原型的好方法,可以更好地了解我正在尝试做的事情。再次感谢。
答案 0 :(得分:1)
您可以使用Apache HttpComponents。这是一个可以在Groovy附带的GroovyConsole中试用的小样本。我使用它是因为它是用于快速原型化的最简单方法,因为使用Grape自动加载库罐(这就是@Grab注释所做的)。此外,在GroovyConsole中,不需要创建项目。你也不需要使用Groovy,尽管我通常会这样做。
请注意,以下代码是从HttpClient Quick Start获取的修改后的POST示例。另外,请注意HttpComponents / HttpClient是一个较新的项目,它取代了Apache的旧版HttpClient(只是在谷歌周围清除它并查看没有HttpComponents的HttpClient)。我使用的主机(posttestserver.com)只是一个接受Http请求的测试服务器,如果一切正常,则返回响应。
@Grab(group='org.apache.httpcomponents', module='httpclient', version='4.2.3')
@Grab(group='org.apache.httpcomponents', module='httpcore', version='4.2.3')
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
String json = "{foo: 123, bar: \"hello\"}";
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://posttestserver.com/post.php");
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();
}