Java sends HTTP requests (submits form form)

Source: Internet
Author: User
Tags readline stringbuffer

http://hbiao68.iteye.com/blog/1973914

Write a servlet for test requests

Java code
  1. Import java.io.IOException;
  2. Import Java.io.PrintWriter;
  3. Import javax.servlet.ServletException;
  4. Import Javax.servlet.http.HttpServlet;
  5. Import Javax.servlet.http.HttpServletRequest;
  6. Import Javax.servlet.http.HttpServletResponse;
  7. Public class ABC extends HttpServlet {
  8. protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
  9. System.out.println ("doget");
  10. This.dopost (request, response);
  11. }
  12. protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
  13. System.out.println ("DoPost");
  14. System.out.println ("AAA:" +request.getparameter ("aaa"));
  15. System.out.println ("param1:" +request.getparameter ("param1"));
  16. System.out.println (Request.getheader ("AVC"));
  17. PrintWriter pw = Response.getwriter ();
  18. Pw.write (Request.getparameter ("param1"));
  19. Pw.flush ();
  20. Pw.close ();
  21. }
  22. }

Web. XML configuration file

XML code
  1. <servlet>
  2. <description></description>
  3. <display-name>abc</display-name>
  4. <servlet-name>abc</servlet-name>
  5. <servlet-class>com. ABC</servlet-class>
  6. </servlet>
  7. <servlet-mapping>
  8. <servlet-name>abc</servlet-name>
  9. <url-pattern>/abc</url-pattern>
  10. </servlet-mapping>

Abstract out a tool request class

Java code
  1. Package http;
  2. Import Java.io.BufferedReader;
  3. Import Java.io.InputStreamReader;
  4. Import Java.io.OutputStreamWriter;
  5. Import java.net.HttpURLConnection;
  6. Import Java.net.URL;
  7. Import Java.util.Map;
  8. Import Java.util.Map.Entry;
  9. Public class Httputil {
  10. public static string http (string URL, map<string, string> params) {
  11. URL u = null;
  12. HttpURLConnection con = null;
  13. //Build request Parameters
  14. StringBuffer sb = new StringBuffer ();
  15. if (params! = null) {
  16. for (entry<string, string> e:params.entryset ()) {
  17. Sb.append (E.getkey ());
  18. Sb.append ("=");
  19. Sb.append (E.getvalue ());
  20. Sb.append ("&");
  21. }
  22. Sb.substring (0, Sb.length ()- 1);
  23. }
  24. System.out.println ("send_url:" + URL);
  25. System.out.println ("send_data:" + sb.tostring ());
  26. //Try to send a request
  27. try {
  28. u = new URL (URL);
  29. Con = (httpurlconnection) u.openconnection ();
  30. ////Post can only be uppercase, strictly limited, post will not recognize
  31. Con.setrequestmethod ("POST");
  32. Con.setdooutput (true);
  33. Con.setdoinput (true);
  34. Con.setusecaches (false);
  35. Con.setrequestproperty ("Content-type", "application/x-www-form-urlencoded");
  36. OutputStreamWriter OSW = new OutputStreamWriter (Con.getoutputstream (), "UTF-8");
  37. Osw.write (Sb.tostring ());
  38. Osw.flush ();
  39. Osw.close ();
  40. } catch (Exception e) {
  41. E.printstacktrace ();
  42. } finally {
  43. if (con! = null) {
  44. Con.disconnect ();
  45. }
  46. }
  47. //Read back content
  48. StringBuffer buffer = new StringBuffer ();
  49. try {
  50. //must have a return value, otherwise the request cannot be sent to the server side.
  51. BufferedReader br = new BufferedReader (new InputStreamReader (Con.getinputstream (), "UTF-8"));
  52. String temp;
  53. While (temp = br.readline ()) = null) {
  54. Buffer.append (temp);
  55. Buffer.append ("\ n");
  56. }
  57. } catch (Exception e) {
  58. E.printstacktrace ();
  59. }
  60. return buffer.tostring ();
  61. }
  62. }

Note: Be sure to get the return value, otherwise the request cannot be reached.

ReadLine () is a blocking method that waits for a response from the server or waits

Con.setdooutput (TRUE); This representation is to send a request to the URL address, without which the server will not respond.

Parameters are passed in a way similar to adding "? key=value&key1=value1" after the URL.

Test class

Java code
  1. @Test
  2. public void Test3 () {
  3. Map parames = new hashmap<string, string> ();
  4. Parames.put ("param1", "Param1_value");
  5. Parames.put ("param2", "Param2_value");
  6. Parames.put ("param3", "Param3_value");
  7. If there is an AAA parameter in the Address bar, the address bar is selected by default, and if not, select the parameter to add
  8. Parames.put ("AAA", "Aaa_value");
  9. Httputil.http ("http://localhost:8080/a/Abc?aaa=dddd", parames);
  10. }

Java sends HTTP requests (submits form form)

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.