Java uses Apache HTTP components to send post requests

Source: Internet
Author: User

In the previous article, the original httpurlconnection in the JDK was used to send a POST request to the specified URL

You can see that the number of encodings is somewhat large and the input and output streams are used

The arguments passed are also passed with a hard-name=xxx string such as "

Here's a look at the Apache HTTP component httpclient in the Apache Commons project

In this way, you can quickly send a request to a URL using a key-value pair of parameters

Package com.newflypig.demo;/** * Use HttpClient to send post requests to URLs using Apache HTTP components * Parameters using key-value pairs to pass */import java.util.ArrayList; Import Java.util.list;import Org.apache.http.httpresponse;import Org.apache.http.namevaluepair;import Org.apache.http.client.httpclient;import Org.apache.http.client.entity.urlencodedformentity;import Org.apache.http.client.methods.httppost;import Org.apache.http.impl.client.httpclients;import Org.apache.http.message.basicnamevaluepair;import Org.apache.http.util.entityutils;public class SendPostDemo2 { public static void Main (string[] args) throws Exception{httpclient Client=httpclients.createdefault (); HttpPost post=new httppost ("Http://localhost:8080/Test1/HelloWorld"); List<namevaluepair> parameters=new arraylist<namevaluepair> ();p Arameters.add (New BasicNameValuePair (" Name "," Ding Ding "));p ost.setentity (new urlencodedformentity (Parameters," UTF-8 ")); HttpResponse Response=client.execute (POST); System.out.println (Entityutils.tostring (Response.getentity ()));}}

Apache HTTP components can be downloaded from http://hc.apache.org/downloads.cgi, the latest version 4.5, with the 3.X version of the use of the method is significantly different.

Using this method regardless of the input and output are encapsulated very comfortable, we can draw on.

Java uses Apache HTTP components to send post requests

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.