Using Java to implement HTTP communication _java

Source: Internet
Author: User
Tags flush readline

Overview of HTTP Communications

HTTP communication has two main ways of post and get. The former sends the data to the server through the HTTP message entity, the security is high, the data transmission size is not limited, the latter passes through the URL the query string to the server parameter, in clear text displays in the browser address bar, the confidentiality is poor, transmits the maximum 2048 characters. But get requests are not useless--get requests are mostly used for querying (reading resources) and are highly efficient. Post requests are used to register, log in, and so on with higher security and write data to the database.

In addition to post and get,http communication there are other ways! See methods for HTTP requests

Pre-coding preparation

Before coding, we create a servlet that receives the parameters of the client (name and age) and responds to the client.

@WebServlet (urlpatterns={"/demo.do"}) public class Demoservlet extends HttpServlet {private static final long Serialv

  Ersionuid = 1L;

    public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
    Request.setcharacterencoding ("Utf-8");
    Response.setcontenttype ("Text/html;charset=utf-8");
    String name = Request.getparameter ("name");
    String age = request.getparameter (' age ');
    PrintWriter pw = Response.getwriter (); Pw.print ("You are requesting the servlet using a Get method.")
    <br/> "+" name = "+ Name +", age = "+ age);
    Pw.flush ();
  Pw.close (); public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioexcepti
    On {request.setcharacterencoding ("utf-8");
    Response.setcontenttype ("Text/html;charset=utf-8");
    String name = Request.getparameter ("name");
    String age = request.getparameter (' age ');
    PrintWriter pw = Response.getwriter (); Pw.print ("You usePost method to request the servlet.
    <br/> "+" name = "+ Name +", age = "+ age);
    Pw.flush ();
  Pw.close ();

 }

}

Implementing HTTP communication using JDK

Using URLConnection to implement GET requests

Instantiate a Java.net.URL object;
A java.net.URLConnection is obtained by the OpenConnection () method of the URL object;
The input stream is obtained by the getInputStream () method of the URLConnection object;
Read the input stream;
Closes the resource.

public void Get () throws exception{url

  url = new URL ("http://127.0.0.1/http/demo.do?name=Jack&age=10");
  URLConnection urlconnection = Url.openconnection ();                          Open Connection
  BufferedReader br = new BufferedReader (New InputStreamReader (Urlconnection.getinputstream (), "Utf-8")); Gets the input stream
  String line = null;
  StringBuilder sb = new StringBuilder ();
  while (line = Br.readline ())!= null) {
    sb.append (line + \ n);
  }

  System.out.println (Sb.tostring ());
}

Using HttpURLConnection to implement post requests

Java.net.HttpURLConnection is a subclass of Java.net.URL that provides more operations on HTTP (GetXXX and Setxxx methods). A series of HTTP status codes is defined in this class:

public void post () throws ioexception{

  url url = new URL ("Http://127.0.0.1/http/demo.do");
  HttpURLConnection httpurlconnection = (httpurlconnection) url.openconnection ();

  Httpurlconnection.setdoinput (true);
  Httpurlconnection.setdooutput (true);    Set the connection to be an
  Httpurlconnection.setrequestmethod ("POST") that can be exported;//Set the request mode
  Httpurlconnection.setrequestproperty ("CharSet", "Utf-8");

  PrintWriter pw = new PrintWriter (New Bufferedoutputstream (Httpurlconnection.getoutputstream ()));
  Pw.write ("Name=welcome");          Output data to the connection (equivalent to sending data to the server)
  pw.write ("&age=14");
  Pw.flush ();
  Pw.close ();

  BufferedReader br = new BufferedReader (New InputStreamReader (Httpurlconnection.getinputstream (), "Utf-8"));
  String line = null;
  StringBuilder sb = new StringBuilder ();
  while (line = Br.readline ())!= null) {  //Read data
    sb.append (line + "\ n");
  }

  System.out.println (Sb.tostring ());
}

Using HttpClient for HTTP communication

HttpClient greatly simplifies the implementation of HTTP communication in JDK.

Maven dependencies:

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId> httpclient</artifactid>
  <version>4.3.6</version>
</dependency>

GET request

public void Httpclientget () throws exception{

  //Create HttpClient object
  httpclient client = Httpclients.createdefault ( );

  Create a GET request (in the constructor to pass in the URL string)
  httpget get = new HttpGet ("http://127.0.0.1/http/demo.do?name=admin&age=40");

  The Execute method that invokes the HttpClient object obtains the response
  httpresponse response = Client.execute (get);

  The GetEntity method that invokes the HttpResponse object gets the response entity
  httpentity httpentity = response.getentity ();

  The string representing the response using the Entityutils tool class represents
  string result = Entityutils.tostring (httpentity, "Utf-8");
  SYSTEM.OUT.PRINTLN (result);
}

POST request

public void Httpclientpost () throws exception{

  //Create HttpClient object
  httpclient client = Httpclients.createdefault ();

  Create POST request
  HttpPost post = new HttpPost ("http://127.0.0.1/http/demo.do");

  Creates a List container that holds the basic key-value pairs (the basic key-value pairs, i.e., parameter names-parameter values)
  list<basicnamevaluepair> parameters = new arraylist<> ();
  Parameters.Add (New Basicnamevaluepair ("name", "John"));
  Parameters.Add (New Basicnamevaluepair ("Age", ")");

  Adds a message entity
  post.setentity (new urlencodedformentity (Parameters, "Utf-8") to the post request);

  Gets the response and translates into a string
  httpresponse response = Client.execute (post);
  Httpentity httpentity = response.getentity ();
  String result = entityutils.tostring (httpentity, "Utf-8");
  SYSTEM.OUT.PRINTLN (result);
}

The

HttpClient is a subproject under Apache Jakarta Common that provides an efficient, up-to-date, feature-rich client-side programming toolkit that supports HTTP protocols, and it supports the latest versions and recommendations of the HTTP protocol. HttpClient has been used in a number of projects, such as the other two famous Jakarta on the Apache Cactus and Htmlunit are using HttpClient.

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.