11
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Java の HttpClient の使い方 (Post)

Last updated at Posted at 2018-02-27

次のページを参考にしました。
Java HTTP通信のサンプル(HttpClient)

Ubuntu 21.04 で確認しました。

Http_post.java
// -----------------------------------------------------------------------
/*
	Http_post.java

				Jul/30/2020
*/
// -----------------------------------------------------------------------
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

// -----------------------------------------------------------------------
class Uri_get {

	static String uri_post_proc(String uri,List<NameValuePair> params)
		{
		String res = "";

		Charset charset = StandardCharsets.UTF_8;

		CloseableHttpClient httpclient = HttpClients.createDefault();
		
		HttpPost request = new HttpPost(uri);

		System.out.println
			("requestの実行 「" + request.getRequestLine() + "」");
		
		CloseableHttpResponse response = null;

		try {
			request.setEntity(new UrlEncodedFormEntity(params));
			response = httpclient.execute(request);
			
			int status = response.getStatusLine().getStatusCode();
			System.out.println("HTTPステータス:" + status);
			//HTTPステータス:200
			
			if (status == HttpStatus.SC_OK){
				
				res = EntityUtils.toString(response.getEntity(),charset);
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				if (httpclient != null) {
					httpclient.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	return res;
	}
}

// -----------------------------------------------------------------------
public class Http_post
{
	public static void main(String[] args)
	{
	String uri = "https://httpbin.org/post";		
	List<NameValuePair> params = new ArrayList<>();
	params.add(new BasicNameValuePair("user","jiro"));
	params.add(new BasicNameValuePair("password","123456"));
		
	String res = Uri_get.uri_post_proc(uri,params);
	System.out.println(res);
	}
}

// -----------------------------------------------------------------------
Makefile
LIB=/usr/share/java
HTTPCLIENT_JAR=.:$(LIB)/httpclient-4.5.13.jar:$(LIB)/httpcore-4.4.14.jar
Http_post.class: Http_post.java
	javac -cp $(HTTPCLIENT_JAR) Http_post.java
clean:
	rm -f *.class

実行コマンド

LIB=/usr/share/java
HTTPCLIENT_JAR=.:$LIB/httpclient-4.5.13.jar:$LIB/httpcore-4.4.14.jar:$LIB/commons-logging-1.2.jar
#
java -cp $HTTPCLIENT_JAR Http_post

実行結果

equestの実行 「POST https://httpbin.org/post HTTP/1.1」
HTTPステータス:200
{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {
    "password": "123456", 
    "user": "jiro"
  }, 
  "headers": {
    "Accept-Encoding": "gzip,deflate", 
    "Content-Length": "25", 
    "Content-Type": "application/x-www-form-urlencoded", 
    "Host": "httpbin.org", 
    "User-Agent": "Apache-HttpClient/4.5.13 (Java/11.0.11)", 
    "X-Amzn-Trace-Id": "Root=1-5f227120-343daab017c55220a4835cd0"
  }, 
  "json": null, 
  "origin": "219.126.139.62", 
  "url": "https://httpbin.org/post"
}

同じことを curl で実行すると

$ curl -X POST https://httpbin.org/post -d 'user=jiro&password=123456'
{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {
    "password": "123456", 
    "user": "jiro"
  }, 
  "headers": {
    "Accept": "*/*", 
    "Content-Length": "25", 
    "Content-Type": "application/x-www-form-urlencoded", 
    "Host": "httpbin.org", 
    "User-Agent": "curl/7.68.0", 
    "X-Amzn-Trace-Id": "Root=1-5f227156-cc1deef43116e768265ffeb8"
  }, 
  "json": null, 
  "origin": "219.126.139.62", 
  "url": "https://httpbin.org/post"
}

Get のサンプルはこちらです。
Java の HttpClient の使い方 (Get)

11
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?