通過Apache的httpClient的post方式串連伺服器,apachehttpclient

來源:互聯網
上載者:User

通過Apache的httpClient的post方式串連伺服器,apachehttpclient



用戶端的代碼是:

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> params = 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 {//實現將請求的參數封裝到表單中,請求體中UrlEncodedFormEntity entity=new UrlEncodedFormEntity(list, encode);//使用post提交資料HttpPost httpPost=new HttpPost(path);//設定使用的EntityhttpPost.setEntity(entity);HttpClient client=new DefaultHttpClient();//用戶端開始向指定的網址發送請求HttpResponse response=client.execute(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;}/** * 將一個輸入資料流轉換成指定編碼的字串 *  * @param inputStream  輸入資料流 * @param encode  編碼格式 * @return  字串 */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;}}

服務端的代碼是:

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");}}}

用戶端的控制台:


-->>longin is success

服務端的控制台:


admin---->username
123----->password


下一篇文章,我將寫通過Apache的httpClient的get方式串連伺服器。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.