Connect to the server through the post method of Apache httpClient, apachehttpclient

Source: Internet
Author: User

Connect to the server through the post method of Apache httpClient, apachehttpclient



The client code is:

Package lgx. java. test; import java. io. byteArrayOutputStream; import java. io. IOException; import java. io. inputStream; import java. io. unsupportedEncodingException; import java. util. arrayList; import java. util. hashMap; import java. util. list; import java. util. map; import org. apache. http. httpResponse; import org. apache. http. nameValuePair; import org. apache. http. client. clientProtocolException; 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. defaultHttpClient; import org. apache. http. message. basicNameValuePair; public class HttpClientDemo {/*** @ param args */public static void main (String [] args) {String path = "http: // 192.168.1.48: 8080/myapp2/LoginAction "; Map <String, String> para MS = new HashMap <String, String> (); params. put ("username", "admin"); params. put ("password", "123"); String result = sendClientPostMessage (path, params, "UTF-8"); System. out. println ("-->" + result);} private static String sendClientPostMessage (String path, Map <String, String> param, String encode) {List <NameValuePair> list = new ArrayList <NameValuePair> (); String result = ""; if (param! = Null &&! Param. isEmpty () {for (Map. entry <String, String> entry: param. entrySet () {list. add (new BasicNameValuePair (entry. getKey (), entry. getValue () ;}}try {// The request parameters are encapsulated in the form. In the request body, UrlEncodedFormEntity entity = new UrlEncodedFormEntity (list, encode ); // use post to submit data HttpPost httpPost = new HttpPost (path); // you can specify the EntityhttpPost. setEntity (entity); HttpClient client = new DefaultHttpClient (); // The client starts to send the request HttpResponse respons to the specified URL E=client.exe cute (httpPost); result = StreamToString (response. getEntity (). getContent (), encode);} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (ClientProtocolException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace ();} return result;}/*** converts an input stream to a specified encoded string * * @ Param inputStream input stream * @ param encode encoding format * @ return String */private static String StreamToString (InputStream inputStream, String encode) {ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream (); byte [] data = new byte [1024]; String result = ""; int len = 0; try {while (len = inputStream. read (data ))! =-1) {arrayOutputStream. write (data, 0, len);} result = new String (arrayOutputStream. toByteArray (), encode);} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace ();} return result ;}}

The server code is:

package com.login.manager;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * Servlet implementation class LoginAction */public class LoginAction extends HttpServlet {private static final long serialVersionUID = 1L;    /**     * Default constructor.      */    public LoginAction() {        // TODO Auto-generated constructor stub    }/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubthis.doPost(request, response);}/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setContentType("text/html;charset=utf-8");request.setCharacterEncoding("utf-8");response.setCharacterEncoding("utf-8");PrintWriter out=response.getWriter();String username=request.getParameter("username");String password=request.getParameter("password");System.out.println(username+"---->username");System.out.println(password+"----->password");if(username.equals("admin")&&password.equals("123")){out.print("longin is success");}else{out.print("login is failed");}}}

Console of the client:


--> Longin is success

Server console:


Admin ----> username
123 -----> password


In the next article, I will write the get method of Apache to connect to the server.

Related Article

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.