Java analog Post form submit httpclient action

Source: Internet
Author: User

  1. Public static void Login () {
  2. String url = "Http://www.***.com/login";
  3. Postmethod Postmethod = new Postmethod (URL);
  4. //Fill in the values of each form field
  5. namevaluepair[] data = {
  6. New Namevaluepair ("account", "[email protected]"),
  7. New Namevaluepair ("Nexturl", " " "),
  8. New Namevaluepair ("Lcallback", " " "),
  9. New Namevaluepair ("password", "******"),
  10. New Namevaluepair ("Persistent", "1"),};
  11. //Put the value of the form into Postmethod
  12. Postmethod.setrequestbody (data);
  13. //Execute Postmethod
  14. int statusCode = 0;
  15. try {
  16. StatusCode = Httpclient.executemethod (Postmethod);
  17. } catch (HttpException e) {
  18. E.printstacktrace ();
  19. } catch (IOException e) {
  20. E.printstacktrace ();
  21. }
  22. //HttpClient for requests to receive subsequent services, such as post and put cannot automatically process forwarding
  23. //301 or 302
  24. if (StatusCode = = httpstatus.sc_moved_permanently
  25. || StatusCode = = httpstatus.sc_moved_temporarily) {
  26. //Remove the turning address from the head
  27. Header Locationheader = Postmethod.getresponseheader ("location");
  28. String location = null;
  29. if (locationheader! = null) {
  30. Location = Locationheader.getvalue ();
  31. System.out.println ("Diandianlogin:" + location);
  32. } Else {
  33. System.err.println ("Location field, value is null.");
  34. }
  35. return;
  36. } Else {
  37. System.out.println (Postmethod.getstatusline ());
  38. String str = "";
  39. try {
  40. str = postmethod.getresponsebodyasstring ();
  41. } catch (IOException e) {
  42. E.printstacktrace ();
  43. }
  44. System.out.println (str);
  45. }
  46. Postmethod.releaseconnection ();
  47. return;
  48. }
  49. One of the jar packages required:
  50. 1, Commons-httpclient.jar
  51. 2, Commons-codec.jar
  52. 3, Commons-logging.jar

Today, when developing, encountered the use of Java HttpClient class to post data, the target received after the Chinese garbled problem.
Request-Side code:

Java code
  1. /**
  2. * HttpClient Submission Parameters
  3. * @author [email protected]
  4. */
  5. Public static void Main (string[] args) throws IOException {
  6. HttpClient client = new HttpClient ();
  7. Client.gethostconfiguration (). Sethost ("127.0.0.1", 8081, "http");
  8. //Submit data using Post
  9. HttpMethod method = Getpostmethod ();
  10. Client.executemethod (method);
  11. //The status returned by the print server
  12. System.out.println (Method.getstatusline ());
  13. //Print results page
  14. String response = new String (Method.getresponsebodyasstring (). GetBytes ("8859_1"));
  15. //Print the returned information
  16. SYSTEM.OUT.PRINTLN (response);
  17. Method.releaseconnection ();
  18. }
  19. Submit data using Post
  20. Private static HttpMethod Getpostmethod () {
  21. String url = "/pushserver/notification.do?action=sendonemsg";
  22. Namevaluepair message = new Namevaluepair ("message", "messaging content.")  ");
  23. Post.setrequestbody (new Namevaluepair[]{message});
  24. return post;
  25. }
  26. Submit data using Get method
  27. Private static HttpMethod Getgetmethod () {
  28. return new GetMethod ("/PUSHSERVER/NOTIFICATION.DO?ACTION=SENDONEMSG&MESSAGE=ABCD");
  29. }


Target-side code:

Java code
  1. /**
  2. * For msgserver Remote Call
  3. * @param request
  4. * @param response
  5. * @return
  6. * @throws Exception
  7. * @author [email protected]
  8. */
  9. Public Modelandview sendonemsg (HttpServletRequest request,
  10. HttpServletResponse response) throws Exception {
  11. String message = Servletrequestutils.getstringparameter (Request, "message");
  12. }


After this code executes, the target can receive the message, but the Chinese garbled, also did not find the Transcoding method.

After analysis, the parameters of the HTTP request that were originally added with Namevaluepair will eventually be converted to requestentity submission to the HTTP server. Then, in Postmethod's parent class, Entityenclosingmethod found that the encoding (character set) of the commit can be set as long as the Getrequestcharset () method is overloaded.

After correction:

Java code
    1. /**
    2. * HttpClient Submission Parameters
    3. * @author [email protected]
    4. */
    5. Public static void Main (string[] args) throws IOException {
    6. HttpClient client = new HttpClient ();
    7. Client.gethostconfiguration (). Sethost ("127.0.0.1", 8081, "http");
    8. //Submit data using Post
    9. HttpMethod method = Getpostmethod ();
    10. Client.executemethod (method);
    11. //The status returned by the print server
    12. System.out.println (Method.getstatusline ());
    13. //Print results page
    14. String response = new String (Method.getresponsebodyasstring (). GetBytes ("8859_1"));
    15. //Print the returned information
    16. SYSTEM.OUT.PRINTLN (response);
    17. Method.releaseconnection ();
    18. }
    19. Submit data using Post
    20. Private HttpMethod Getpostmethod () {
    21. String url = "/pushserver/notification.do?action=sendonemsg";
    22. Postmethod post = new Utf8postmethod (URL);
    23. Namevaluepair message = new Namevaluepair ("message", "messaging content.")  ");
    24. Post.setrequestbody (new Namevaluepair[]{message});
    25. return post;
    26. }
    27. Inner Class for UTF-8 support
    28. Public static class Utf8postmethod extends postmethod{
    29. Public utf8postmethod (String url) {
    30. super (URL);
    31. }
    32. @Override
    33. Public String Getrequestcharset () {
    34. //return Super.getrequestcharset ();
    35. return "UTF-8";
    36. }
    37. }
    38. Submit data using Get method
    39. Private static HttpMethod Getgetmethod () {
    40. return new GetMethod ("/PUSHSERVER/NOTIFICATION.DO?ACTION=SENDONEMSG&MESSAGE=ABCD");
    41. }

Java analog Post form submit httpclient action

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.