httpClient学习笔记1

客服端以post请求输入xml的输入流,来到服务器端,服务器端接到输入流,进行处理,处理完毕后,返回xml信息的返回输出流,来告诉对方成功与否。

htppClient的使用至少需要commons-httpclient-3.1.jar,commons-logging-1.0.4.jar,commons-codec-1.3.jar三个Apache开源项目jar包的支持。(jar的版本可以不同,我用的是如上三个。)

模拟客户端代码:

package httpClientDemo;
import java.io.File;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.FileRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;


public class HttpClientTest {
   private static final String  LOGON_SITE = "localhost" ;
   private static final int     LOGON_PORT = 8080;


    @SuppressWarnings("deprecation")
  public static void main(String[] args) throws Exception {
        File input = new File("d:\test.xml");
        PostMethod post = new PostMethod("/Mytest/servlet/abc.do");
       NameValuePair name = new NameValuePair( "name" , "zhangjinping" );
       NameValuePair pass = new NameValuePair( "password" , "123456" );
        post.setRequestBody( new NameValuePair[]{name,pass});

        HttpClient client = new HttpClient();
        client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT);
  
       
        
                RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=utf-8");
              //  post.setRequestHeader( "Content-type" , "text/xml; charset=utf-8" );
                post.setRequestEntity(entity);
                try {
        
                   int result = client.executeMethod(post);

                   System.out.println("Response status code: " + result);

                   System.out.println("Response body: ");
        
                   System.out.println(post.getResponseBodyAsString());
        
                } finally {
        
                    post.releaseConnection();
        
                }
              

      /*  // 设置请求的内容直接从文件中读取
        post.setRequestBody( new FileInputStream(input));
        if (input.length() < Integer.MAX_VALUE)
           post.setRequestContentLength(input.length());
        else
           post.setRequestContentLength(EntityEnclosingMethod.CONTENT_LENGTH_CHUNKED);
 
        // 指定请求内容的类型
    
      
        int result =client.executeMethod(post);
        System.out.println( "Response status code: " + result);
        System.out.println( "Response body: " );
        System.out.println(post.getRequestCharSet());
        System.out.println(post.getResponseBodyAsString());
        post.releaseConnection();
     } */
 
    }

}

服务器端代码:

package web;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import pojo.Student;
import bo.CreateBD;

import common.CreateXMLUtil;

public class AjaxTestServlet extends HttpServlet {

 /**
  * Constructor of the object.
  */
 public AjaxTestServlet() {
  super();
 }

 /**
  * Destruction of the servlet. <br>
  */
 public void destroy() {
  super.destroy(); // Just puts "destroy" string in log
  // Put your code here
 }

 /**
  * The doGet method of the servlet. <br>
  *
  * This method is called when a form has its tag value method equals to get.
  *
  * @param request the request send by the client to the server
  * @param response the response send by the server to the client
  * @throws ServletException if an error occurred
  * @throws IOException if an error occurred
  */
 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
           doPost(request, response);
 }

 /**
  * The doPost method of the servlet. <br>
  *
  * This method is called when a form has its tag value method equals to post.
  *
  * @param request the request send by the client to the server
  * @param response the response send by the server to the client
  * @throws ServletException if an error occurred
  * @throws IOException if an error occurred
  */
 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>.");
  String str = request.getParameter("testPost");
  String name= request.getParameter("name");
  String password = request.getParameter("password");
  System.out.println(name+"  "+password);
  @SuppressWarnings("unused")
  StringBuffer sb = new StringBuffer();
  InputStream is= request.getInputStream();
  
  InputStreamReader isr = new InputStreamReader(is);
  BufferedReader br = new BufferedReader(isr);
  while(true){
        str = br.readLine();
        if(str!=null)
         sb.append(str);
        if(str==null)
         break;
   }
  
  System.out.println(sb.toString());
  
  response.setContentType("application/xml"); //application/xml代表的是XML形式返回
  response.setHeader("Cache-Control", "no-cache"); //设置不缓存
       
  List<Student> students = CreateBD.getData();
  //组织返回数据
  String xml=CreateXMLUtil.getClassXML(students, "students");

  PrintWriter pw=null;
  try {
  //获取页面写入器
  pw=response.getWriter();
  } catch (IOException e) {
  e.printStackTrace();
  }
  pw.write(xml);
  pw.flush();
  pw.close();
 

 }

 /**
  * Initialization of the servlet. <br>
  *
  * @throws ServletException if an error occurs
  */
 public void init() throws ServletException {
  // Put your code here
 }

}

Apache官方:httpClient 详解:

http://hc.apache.org/httpclient-3.x/

Apache官方:httpClient使用xmlPOST的举例代码:http://svn.apache.org/viewvc/httpcomponents/oac.hc3x/trunk/src/examples/

原文地址:https://www.cnblogs.com/alaricblog/p/3278275.html