HttpClient 4.1.3 Beginner---Simple page with Get and post emulation (with parameters respectively)

Source: Internet
Author: User

Recently need to solve the problem need to use httpclient, simulation landing site! After success, you can use the code to get the content of the site or send a request, like a web crawler.

But on the internet to find a lot of blog, found that each piece of writing are not the same, also tangled up some time, very puzzled, just found httpclient version is not the same ... Now here I am using the version is HttpClient 4.1.3, I have uploaded the download

Read some blog, found that direct access to large sites is not easy, so they wrote a small site, only a servlet, to accept parameters (user name and password) OK!

This servlet has only get and post methods, and the method is as follows

<span style= "Font-family:microsoft yahei;font-size:14px;" >public class Loginservlet extends HttpServlet {public void doget (HttpServletRequest request, HttpServletResponse Response) throws Servletexception, IOException {response.setcontenttype ("text/html"); PrintWriter out = Response.getwriter (); String name = Request.getparameter ("name"); String psd = request.getparameter ("pwd"), if ("Wang". Equals (name) && "123". Equals (PSD)) {Out.print ("true");} Else{out.print ("false");}} public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { This.doget (request, response);} </span>
The simple "server" is set up, followed by the client using the HttpClient simulation login!

First, analyze the URL that you want to log in to successfully: http://localhost:8080/HttpServer/LoginServlet?name=wang&pwd=123

The parameters are two ("name", "Wang") and ("pwd", "123");

Next is the Httpclent debut!!!

    • Create Client

<span style= "Font-family:microsoft yahei;font-size:14px;" >httpclient client = new Defaulthttpclient ();</span>

    • Choose how you send the request

<span style= "Font-family:microsoft yahei;font-size:14px;" >httppost HttpPost = new HttpPost (URL); The method of sending the request, here is posthttpget httpget = new HttpGet (URL);                                                              The method of sending the request, here is get</span>

    • To set parameters , post and get add parameters in different ways, the following code gives
    • Send Request

<span style= "Font-family:microsoft yahei;font-size:14px;" >       HttpResponse response = Client.execute (httppost); </span>
The server receives the request to make the response and the related HTML content is in the response, depends on how to use!

Here is the code

<span style= "Font-family:microsoft yahei;font-size:14px;" >private static void Postmethd () throws Unsupportedencodingexception,ioexception, Clientprotocolexception {                         HttpClient client = new Defaulthttpclient (); Create Clenthttppost HttpPost = new HttpPost (URL);     The method of sending the request, here is postlist<namevaluepair> formparams = new arraylist<namevaluepair> (); The method of adding a parameter by post is Formparams.add (new Basicnamevaluepair ("name", name)), Formparams.add (New Basicnamevaluepair ("pwd", PWD));           Urlencodedformentity uefentity;uefentity = new Urlencodedformentity (formparams, "UTF-8"); Prevent garbled, plus utf-8httppost.setentity (uefentity);                    HttpResponse response = Client.execute (HttpPost);                              Submit Request InputStream in = Pringstatus (response);                                                          In.close ();                            Turn off the output stream Client.getconnectionmanager (). Shutdown (); Close client}private static void Getmethd () throws UnsupportedenCodingexception,ioexception, clientprotocolexception {HttpClient client = new Defaulthttpclient ();                           StringBuilder sb = new StringBuilder (URL); Here is a GET request, the method of adding parameters is a bit complicated, but I did not find a good method, Sb.append ("?"); Also please crossing sb.append ("Name="). Append (name); Sb.append ("&&"); Sb.append ("pwd="). Append (PWD); HttpGet httpget = new HttpGet (sb.tostring ()); HttpResponse response = Client.execute (httpget); InputStream in = Pringstatus (response); In.close (); Client.getconnectionmanager (). shutdown ();} private static InputStream Pringstatus (HttpResponse response) throws IOException, Unsupportedencodingexception {  System.out.println (Response.getstatusline (). toString ()); After the request is sent, the server responds with a status of inputstream in = Response.getentity (). getcontent ();                          BufferedReader br = new BufferedReader (new InputStreamReader (in, "Utf-8")); String line = null;while (line = Br.readline ())!=null) {System.out.println (line.tostring ());} return in;} </span>
OK, open Tomcat and run to verify success!

<span style= "Font-family:microsoft yahei;font-size:14px;" >http/1.1 oktrue</span>
The first line is the state of the server response, and the second line is the HTML content, because the servlet is

<span style= "Font-family:microsoft yahei;font-size:14px;" >out.print ("true");</span>

Here, httpclient simulation login Simple website is finished, next I will continue to learn to use the HttpClient login website, and keep cookies, send requests and resolution and other related content!
Code download



HttpClient 4.1.3 Beginner---Simple page with Get and post emulation (with parameters respectively)

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.