封装的http的doPost请求和doGet请求

1.maven依赖:

		
			org.apache.commons
			commons-lang3
			3.4
		
		
		
            commons-logging
            commons-logging
            1.1.3
        
		
		    org.apache.httpcomponents
		    httpclient
		    4.2.1
		
		
		
			org.apache.httpcomponents
			httpcore
			4.2.1
		
		
			log4j
			log4j
			1.2.17
		


2.工具包代码:

/**     
 * @文件名称: HttpUtil.java   
 * @描述: TODO  
 * @作者:  wuwh
 * @时间:2018年4月9日 上午11:08:27  
 * @版本:V1.0     
 */ 
package com.skiff.www;



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

/**  
 * @类功能说明:    封装的http的doPost()和doGet()方法
 * 需要依赖的jar包:
 * 				commons-lang3-3.4.jar
 *              commons-logging-1.2.jar
 *              httpclient-4.3.5.jar
 *              httpcore-4.4.1.jar
 *              log4j-1.2.17.jar
 * @作者: wuwh
 * @创建时间:2018年4月9日 上午11:08:27  
 * @版本:V1.0  
 */
public class HttpUtil {
	private static Logger logger = Logger.getLogger(HttpUtil.class);

	/**  
	 * 方法功能说明:    http的doGet请求
	 * @参数: @param url  
	 * @参数: @param map
	 * @参数: @return      
	 * @return String     
	 * @throws  
	 */ 
	public static String doGet(String url,Map map) {
		String params = HttpUtil.formatUrlMap(map, false, false);
		//拼接成的带参数的url
		url = url+"?"+params;
        try {
        	HttpClient client = new DefaultHttpClient();
            //发送get请求
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);
 
            /**请求发送成功,并得到响应**/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                /**读取服务器返回过来的json字符串数据**/
                String strResult = EntityUtils.toString(response.getEntity());
                
                return strResult;
            }
        } 
        catch (IOException e) {
        	 logger.error("HttpUtil.doGet():出错了",e);
        	
        }
        
        return null;
	}
	
	/**
	 * post请求(用于key-value格式的参数)
	 * @param url
	 * @param params
	 * @return
	 */
	public static String doPost(String url, Map params){
		BufferedReader in = null;  
        try {  
            // 定义HttpClient  
            HttpClient client = new DefaultHttpClient();  
            // 实例化HTTP方法  
            HttpPost request = new HttpPost();  
            request.setURI(new URI(url));
            
            //设置参数
            List nvps = new ArrayList(); 
            for (Iterator iter = params.keySet().iterator(); iter.hasNext();) {
    			String name = (String) iter.next();
    			String value = String.valueOf(params.get(name));
    			nvps.add(new BasicNameValuePair(name, value));
    			
    			//System.out.println(name +"-"+value);
    		}
            request.setEntity(new UrlEncodedFormEntity(nvps,HTTP.UTF_8));
            
            HttpResponse response = client.execute(request);  
            int code = response.getStatusLine().getStatusCode();
            if(code == 200){	//请求成功
            	in = new BufferedReader(new InputStreamReader(response.getEntity()  
                        .getContent(),"utf-8"));
                StringBuffer sb = new StringBuffer("");  
                String line = "";  
                String NL = System.getProperty("line.separator");  
                while ((line = in.readLine()) != null) {  
                    sb.append(line + NL);  
                }
                
                in.close();  
                
                return sb.toString();
            }
            else{	//
            	 logger.error("HttpUtil.doPost():状态码:"+ code);
            	return null;
            }
        }
        catch(Exception e){
        	 logger.error("HttpUtil.doPost():出错了",e);
        	
        	return null;
        }
	}
	
	  /** 
     *  
     * 方法用途: 对所有传入参数按照字段名的Unicode码从小到大排序(字典序),并且生成url参数串
* 实现步骤:
* * @param paraMap 要排序的Map对象 * @param urlEncode 是否需要URLENCODE * @param keyToLower 是否需要将Key转换为全小写 * true:key转化成小写,false:不转化 * @return */ public static String formatUrlMap(Map paraMap, boolean urlEncode, boolean keyToLower) { String buff = ""; Map tmpMap = paraMap; try { List> infoIds = new ArrayList>(tmpMap.entrySet()); // 对所有传入参数按照字段名的 ASCII 码从小到大排序(字典序) Collections.sort(infoIds, new Comparator>() { @Override public int compare(Map.Entry o1, Map.Entry o2) { return (o1.getKey()).toString().compareTo(o2.getKey()); } }); // 构造URL 键值对的格式 StringBuilder buf = new StringBuilder(); for (Map.Entry item : infoIds) { //StringUtils类需要依赖commons-lang3.jar包 if (StringUtils.isNotBlank(item.getKey())) { String key = item.getKey(); String val = item.getValue(); if (urlEncode) { val = URLEncoder.encode(val, "utf-8"); } if (keyToLower) { buf.append(key.toLowerCase() + "=" + val); } else { buf.append(key + "=" + val); } buf.append("&"); } } buff = buf.toString(); if (buff.isEmpty() == false) { buff = buff.substring(0, buff.length() - 1); } } catch (Exception e) { logger.error("HttpUtil.formatUrlMap():出错了",e); return null; } return buff; } }

3.调用代码:


/**     
 * @文件名称: HttpUtilTest.java   
 * @描述: TODO  
 * @作者:  wuwh
 * @时间:2018年4月9日 上午11:28:00  
 * @版本:V1.0     
 */ 
package com.skiff.www;

import java.util.HashMap;
import java.util.Map;

/**  
 * @类功能说明:    
 * @作者: wuwh
 * @创建时间:2018年4月9日 上午11:28:00  
 * @版本:V1.0  
 */
public class HttpUtilTest {
	
	public static void main1(String[] args) {
		Map map = new HashMap<>();
		map.put("token", "XTIeQIE7wg4bGMF4fAbi");
		map.put("openId", "");
		map.put("mobilePhone", "15011222345");
		map.put("id", "47");
		String url = "http://120.78.190.109:8087/app/scenic/detail";
		String result = HttpUtil.doGet(url,map);
		System.out.println(result);
	}


	
	public static void main(String[] args) {
		String url = "http://120.78.190.109:8087/app/scenic/detail";
		Map map = new HashMap<>();
		map.put("token", "XTIeQIE7wg4bGMF4fAbi");
		map.put("openId", "");
		map.put("mobilePhone", "15011222345");
		map.put("id", "47");
		String result = null;
		try {
			result = HttpUtil.doPost(url, map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println(result);
	}
}





你可能感兴趣的:(java)