0
0

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 5 years have passed since last update.

HttpClient 4.x : POST

Posted at
package hello.httpclient4x;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
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;

public class HelloPostMain {

	public static void main(String[] args) throws Exception {

		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {

			List<NameValuePair> params = new ArrayList<NameValuePair>();

			params.add(new BasicNameValuePair("key1", "value1"));

			HttpPost httpPost = new HttpPost(
					"http://localhost:8080/HelloWeb/index.jsp");
			httpPost.setEntity(new UrlEncodedFormEntity(params));

			System.err
					.println("Executing request " + httpPost.getRequestLine());

			CloseableHttpResponse response = httpclient.execute(httpPost);
			try {
				System.err.println(response.getStatusLine());
				// EntityUtils.consume(response.getEntity());

				System.err.println(response.getStatusLine().getStatusCode());

				Header[] headers = response.getAllHeaders();
				for (Header header : headers) {
					System.err.println(header.getName() + ": "
							+ header.getValue());
				}

				HttpEntity httpEntity = response.getEntity();
				System.err.println(EntityUtils.toString(httpEntity));

			} finally {
				response.close();
			}
		} finally {
			httpclient.close();
		}
	}

}

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?