HttpClient使用详解

                     这段时间有些忙,写的文章讲的没有那么细,不过尽量分享给大家,今天说下httpClient的使用。

客户端依赖:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.2</version>
</dependency>
    <dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient-cache</artifactId>
    <version>4.5.2</version>
</dependency>
    <dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.5.2</version>
</dependency>

客户端的代码:

package com.alibaba.test.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.CharArrayBuffer;
import org.apache.http.util.EntityUtils;
/**
 * @author cwc
 * @date 2018年7月16日  
 * @version 1.0.0 
 * @description:http post使用
 */
public class HttpClientUtil {
	
	public static void main(String[] args) {
		
		String jsons=readFileContent("D:/home/a.txt");//从文本中读取json数据
		String url="http://192.168.100.6:8080/detail/index.htm";//接口
		Map< String, String> map =new HashMap<String, String>();//定义一个map存储参数
		map.put("mkdirName", "/M1");
		map.put("fileName", "/M1/one.txt");
		map.put("catFile", "/M1/one.txt");
		map.put("jsons", jsons);//我讲json封装到了map中,功能实现了,但不知道以后有影响没。
		getHttpData(url,map);
	}

	/**
	 * 使用post方法
	 */
	public static void getHttpData(String url,Map<String, String> map){
		 //1.使用默认的配置的httpclient
		String result =null;
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
//        InputStream inputStream = null;
        CloseableHttpResponse response = null;
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
   	 	for(Map.Entry<String,String> entry : map.entrySet()){
   		 pairs.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
   		 }

        try {
        	post.setEntity(new UrlEncodedFormEntity(pairs,"UTF-8"));//这句解决了乱码
        	//3.执行请求,获取响应
			response = client.execute(post);
			//看请求是否成功,这儿打印的是http状态码
            System.out.println("状态:"+response.getStatusLine().getStatusCode());
            //4.获取响应的实体内容,就是我们所要抓取得网页内容
            HttpEntity entity = response.getEntity();
            //5.将其打印到控制台上面
            result = entityToString(entity);
            System.out.println("result:---------->"+result);
            
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 读取txt中的json
	 * @param fileName
	 * @return
	 * @throws IOException
	 */
	 private static String readFileContent(String fileName) {
		  File file = new File(fileName);
		  BufferedReader bf;
		try {
			bf = new BufferedReader(new FileReader(file));
			  String content = "";
			  StringBuilder sb = new StringBuilder();
			  
			  while((content=bf.readLine())!= null){
			   content = new String (content.getBytes("UTF-8"));
			   if(content == null){
			    break;
			   }
			   sb.append(content.trim());
			  }
			bf.close();
			return sb.toString();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		  return null;
		
	}
	 
	 /**
	  * 转化为字符串
	  * @param entity
	  * @return
	  * @throws IOException
	  */
	 private static String entityToString(HttpEntity entity) throws IOException {
	        String result = null;
	        if(entity != null)
	        {
	            long lenth = entity.getContentLength();
	            if(lenth != -1 && lenth < 2048)
	            {
	                result = EntityUtils.toString(entity,"UTF-8");
	            }else {
	                InputStreamReader reader1 = new InputStreamReader(entity.getContent(), "UTF-8");
	                CharArrayBuffer buffer = new CharArrayBuffer(2048);
	                char[] tmp = new char[1024];
	                int l;
	                while((l = reader1.read(tmp)) != -1) {
	                    buffer.append(tmp, 0, l);
	                }
	                result = buffer.toString();
	            }
	        }
	        return result;
	    }
}

服务端依赖:

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
	</dependency>

服务端代码:



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;

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

/**
 * Alibaba Group EDAS. http://www.aliyun.com/product/edas
 */
public class IndexServlet extends HttpServlet {

	private static final long serialVersionUID = -112210702214857712L;

	
	@Override
	public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
		
		//判断请求报文是否来自代维系统的ip地址
		String ip = request.getRemoteHost();
		System.out.println(ip);
		//之前看到说流只能获取一次,过多的调用方法会造成获取不到数据
		String mkdirName =request.getParameter("mkdirName");
		String fileName =request.getParameter("fileName");
		String catFile =request.getParameter("catFile");
		System.out.println("要查看的文件"+catFile);
		String jsonss=request.getParameter("jsons");
		System.out.println("获取的json----------->"+jsonss);
		
		
		// 设置发送报文的格式
		response.setContentType("text/html;charset=utf-8");
	    response.setCharacterEncoding("utf-8");
	    request.setCharacterEncoding("utf-8");
	    //如果请求验证合格,则根据请求的参数装配返回的报文
	  		final StartListener sl =new StartListener();//调用别的类的方法
	  		
	  		
	  		
	  		//能否将返回结果封装到map中,我如果需要返回结果的怎么拿我想要的返回结果呢。
	  		if(mkdirName!=null&&!mkdirName.equals("")){
	  			System.out.println("开始创建目录!");
	  			resultBuffer.append(sl.mkdir(mkdirName));
	  		}
	  		
	  		if(fileName!=null&&!fileName.equals("")){
	  			System.out.println("开始创建文件!!!");
	  			resultBuffer.append(sl.creates(fileName, jsonss));
	  		}
	  		
	  		if(catFile!=null&&!catFile.equals("")){
	  			System.out.println("查看文件!!!");
	  			resultBuffer.append(sl.catFile(catFile));
	  		}
	  		
	  		
	  		PrintWriter out = response.getWriter();
	  		out.println(resultBuffer.toString());
	  		out.flush();
	  		out.close();
	}
	
	
	
	@Override
	protected void doPost( HttpServletRequest req, HttpServletResponse resp ) throws ServletException, IOException {
	doGet(req, resp);
	}

}


httpClient要比URLConnection好用的多,数据交互要学习的还有很多,继续努力。

 

posted @ 2018-07-16 20:53  wanchen  阅读(166)  评论(0编辑  收藏  举报