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

ApacheHttpComponentsを使用できます。これは、Groovyに付属のGroovyConsoleで試すことができる小さなサンプルです。Grapeを使用したライブラリjarの自動ロードにより、何かをすばやくプロトタイプ化する最も簡単な方法であるため、これを使用します(@Grabアノテーションが行うことです)。また、GroovyConsoleでは、プロジェクトを作成する必要はありません。私は通常使用しますが、Groovyを使用する必要もありません。

以下のコードは、 HttpClientクイックスタートから取得した変更されたPOSTの例であることに注意してください。また、HttpComponents / HttpClientは、Apacheの古いHttpClientに取って代わる新しいプロジェクトであることに注意してください(Googleを使用して、HttpComponentsのないHttpClientが表示された場合に備えて、これをクリアしてください)。私が使用したホスト(posttestserver.com)は、Http要求を受け入れ、すべてがOKの場合に応答を返すテストサーバーです。

@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 に答える