[Java] HttpClient の POST で JSON を送信する件.

NO IMAGE

任意のパスにある JSON ファイルを読み込みます.
それを HttpClient を使用して POST メソッド JSON リクエストとしてサーバに送りつけます.
サーバは Play Framework で.
という例の HttpClient 側です.

package com.example.example_post_json_by_httpclient;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class Main {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub

		DefaultHttpClient httpClient = new DefaultHttpClient();
		
		HttpPost request = new HttpPost("http://example.test:9000/post");
		
		String strJson = "";
		
		String path = "/path/to/test.json";
		BufferedReader br = new BufferedReader(new FileReader(new File(path)));
		String str;
		while((str = br.readLine()) != null){
			strJson += str;
		}
		System.out.println(strJson);
		
		StringEntity body = new StringEntity(strJson);
		request.addHeader("Content-type", "application/json");
		request.setEntity(body);
		
		String result = httpClient.execute(request, new ResponseHandler<String>(){
			public String handleResponse(HttpResponse response) throws IOException{
				switch(response.getStatusLine().getStatusCode()){
				case HttpStatus.SC_OK:
					System.out.println(HttpStatus.SC_OK);
					return EntityUtils.toString(response.getEntity(), "UTF-8");
				case HttpStatus.SC_NOT_FOUND:
					System.out.println(HttpStatus.SC_NOT_FOUND);
					return "404";
				default:
					System.out.println("unknown");
					return "unknown";
				}
			}
		});
		System.out.println(result);
		httpClient.getConnectionManager().shutdown();
	}
}

https://github.com/ReactiveMongo/Play-ReactiveMongo

Javaカテゴリの最新記事