0

我见过几个人拿一个字符串并将其用作 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();
}

这对我来说是一个很好的快速健全性检查,是一种快速原型化的好方法,可以更好地了解我正在尝试做的事情。再次感谢。

4

1 回答 1

1

您可以使用 Apache HttpComponents。这是一个小示例,您可以在 Groovy 附带的 GroovyConsole 中试用。我使用它是因为它是快速原型化的最简单方法,因为使用 Grape 自动加载库 jar(这就是 @Grab 注释所做的)。此外,在 GroovyConsole 中,无需创建项目。您也不需要使用 Groovy,尽管我通常会这样做。

请注意,下面的代码是从HttpClient Quick Start中获取的修改后的 POST 示例。另外,请注意 HttpComponents/HttpClient 是一个较新的项目,它取代了来自 Apache 的旧 HttpClient(如果您在 Google 周围搜索并看到没有 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();
}
于 2013-03-08T20:14:59.747 回答