Http请求工具类HttpUtil

阅读更多

 

httpGet + hostname in certificate didn't match   报错!

HTTPS加密引起的。

解决https需要验证问题

Hostname in certificate didn't match?

HttpClient工具类

 

两种方式:

GET、SET


Http请求工具类HttpUtil_第1张图片
 

try	
		{
			String strRequest=cdoRequest.toXML();
			String strTransName = cdoRequest.getStringValue("strTransName");
			String _strURL = strUrl + "?strTransName=" + strTransName + "&$$CDORequest$$=" + java.net.URLEncoder.encode(strRequest,"UTF-8");
			if(_strURL.length()>=1024)
			{
				httpClient = new HttpClient(HttpClient.TRANSMODE_FORM,HttpClient.METHOD_POST);
				Map paramMap = new HashMap();
				paramMap.put("strTransName",cdoRequest.getStringValue("strTransName"));
				paramMap.put("$$CDORequest$$",strRequest);
				httpClient.setUrl(strUrl);
				httpClient.setNameValuePair(paramMap);
			}
			else 
			{
				httpClient = new HttpClient(HttpClient.TRANSMODE_FORM,HttpClient.METHOD_GET);
				httpClient.setUrl(_strURL);			
			}
			strCDOXml = httpClient.getResponseString();
		}catch(Exception ex)
		{
			logger.error(ex.getMessage(), ex); 		
			return Return.valueOf(-1," http Status:"+httpClient.getStatus()+";Send Http Request ERROR:"+ex.getMessage());	
		} 

 

 

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.log4j.Logger;

public class HttpUtil {
	private static final Logger logger = Logger.getLogger(HttpUtil.class);
	/**
	 * http post请求
	 * @param url						地址
	 * @param postContent				post内容格式为param1=value¶m2=value2¶m3=value3
	 * @return
	 * @throws IOException
	 */
	public static String httpPostRequest(URL url, String postContent) throws Exception{
		OutputStream outputstream = null;
		BufferedReader in = null;
		try
		{
			URLConnection httpurlconnection = url.openConnection();
			httpurlconnection.setConnectTimeout(10 * 1000);
			httpurlconnection.setDoOutput(true);
			httpurlconnection.setUseCaches(false);
			OutputStreamWriter out = new OutputStreamWriter(httpurlconnection
					.getOutputStream(), "UTF-8");
			out.write(postContent);
			out.flush();
			
			StringBuffer result = new StringBuffer();
			in = new BufferedReader(new InputStreamReader(httpurlconnection
					.getInputStream(),"UTF-8"));
			String line;
			while ((line = in.readLine()) != null)
			{
				result.append(line);
			}
			return result.toString();
		}
		catch(Exception ex){
			logger.error("post请求异常:" + ex.getMessage());
			throw new Exception("post请求异常:" + ex.getMessage());
		}
		finally
		{
			if (outputstream != null)
			{
				try
				{
					outputstream.close();
				}
				catch (IOException e)
				{
					outputstream = null;
				}
			}
			if (in != null)
			{
				try
				{
					in.close();
				}
				catch (IOException e)
				{
					in = null;
				}
			}
		}	
	}	
	
	/**
	 * 通过httpClient进行post提交
	 * @param url				提交url地址
	 * @param charset			字符集
	 * @param keys				参数名
	 * @param values			参数值
	 * @return
	 * @throws Exception
	 */
	public static String HttpClientPost(String url , String charset , String[] keys , String[] values) throws Exception{
		HttpClient client = null;
		PostMethod post = null;
		String result = "";
		int status = 200;
		try {
	           client = new HttpClient();                
               //PostMethod对象用于存放地址
             //总账户的测试方法
               post = new PostMethod(url);         
               //NameValuePair数组对象用于传入参数
               post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=" + charset);//在头文件中设置转码

               String key = "";
               String value = "";
               NameValuePair temp = null;
               NameValuePair[] params = new NameValuePair[keys.length];
               for (int i = 0; i < keys.length; i++) {
            	   key = (String)keys[i];
            	   value = (String)values[i];
            	   temp = new NameValuePair(key , value);   
            	   params[i] = temp;
            	   temp = null;
               }
              post.setRequestBody(params); 
               //执行的状态
              status = client.executeMethod(post); 
              logger.info("status = " + status);
               
              if(status == 200){
            	  result = post.getResponseBodyAsString();
              }
               
		} catch (Exception ex) {
			// TODO: handle exception
			throw new Exception("通过httpClient进行post提交异常:" + ex.getMessage() + " status = " + status);
		}
		finally{
			post.releaseConnection(); 
		}
		return result;
	}
	
	/**
	 * 字符串处理,如果输入字符串为null则返回"",否则返回本字符串去前后空格。
	 * @param inputStr			输入字符串
	 * @return	string 			输出字符串
	 */
    public static String doString(String inputStr){
    	//如果为null返回""
        if(inputStr == null || "".equals(inputStr) || "null".equals(inputStr)){
    		return "";
    	}	
        //否则返回本字符串把前后空格去掉
    	return inputStr.trim();
    }

    /**
     * 对象处理,如果输入对象为null返回"",否则则返回本字符对象信息,去掉前后空格
     * @param object
     * @return
     */
    public static String doString(Object object){
    	//如果为null返回""
        if(object == null || "null".equals(object) || "".equals(object)){
    		return "";
    	}	
        //否则返回本字符串把前后空格去掉
    	return object.toString().trim();
    }
    
}

 

使用:

String returnXML = HttpUtil.httpPostRequest(new URL(sendURL), postContent);

 

 工具类2:

public class HttpUtil {
	private static Log log = LogFactory.getLog(HttpUtil.class);

	private static final String DEFAULT_HTTP_CHARSET = "UTF-8";
	
	private static final String GETID_URL = ProPertiesUtil.getValue("/server.properties", "getidurl");
	
	private static DefaultHttpClient httpClient = new DefaultHttpClient();

	private HttpUtil() {}
	
	
	public static String sendHttpByPost(String url,Map map) throws Exception{
		HttpClient httpClient = new HttpClient(HttpClient.TRANSMODE_FORM,HttpClient.METHOD_POST);
		/*Map paramMap = new HashMap();
		paramMap.put("wf_type_id",wf_type_id.toString());
		paramMap.put("customer_id",customer_id.toString());
		paramMap.put("thirdparty_id",thirdparty_id.toString());
		paramMap.put("order_no",order_no);
		paramMap.put("order_idss",order_idss);
		paramMap.put("user_id",user_id.toString());
		paramMap.put("wf_code",wf_code);
		paramMap.put("step",step.toString());
		paramMap.put("wf_id", wf_id.toString());*/
		
		httpClient.setUrl(url);
		httpClient.setNameValuePair(map);
	
		return  httpClient.getResponseString();
		
	}
	
	public static String httpGet(String url) {
		String strReturn = "";
		HttpUriRequest request = new HttpGet(url);
		try {
			HttpResponse response = httpClient.execute(request);
			HttpEntity entity = response.getEntity();
			strReturn = EntityUtils.toString(entity,DEFAULT_HTTP_CHARSET);
		}catch(Exception e) {
			// 网络异常
			log.error(e.getMessage());
		}
		return strReturn;
	}
	
	
	public static void main(String[] args) throws JSONException, Exception{
		
		String strUrl1 = "http://localhost:8084/test/order/addOrder.do?orderCode=123456789&totalFee=39800";
		System.out.println(httpGet(strUrl1));
	}
	
}

 

或:

public String getMedia(String token,String mediaID){
		logger.info("getMedia=============start");
		String url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token="+token+"&media_id="+mediaID;
    	
    	BufferedInputStream bis = null;
    	FileOutputStream fos = null;
    	String imgFilePath = null;
		try {
           HttpClient client = new DefaultHttpClient();  
           HttpGet httpGet = new HttpGet(url);  
           HttpResponse response = client.execute(httpGet); 
           HttpEntity entity = response.getEntity();  
           
           
           // 根据内容类型获取扩展名
           String fileExt = getFileEndWitsh(entity.getContentType().getValue());
           if(StringUtils.isEmpty(fileExt)) {
        	   logger.error("上传图片出错:content-Type" +entity.getContentType().getValue() + EntityUtils.toString(entity, "UTF-8"));
        	   return null;
           }
           String tmpImgPath = ProPertiesUtil.getValue("/auction.properties", "tmp_img_path");
           
   		   imgFilePath = getPhysicalPath(tmpImgPath) + File.separator + mediaID + fileExt;;// 新生成的图片
   		
           bis = new BufferedInputStream(entity.getContent());
           fos = new FileOutputStream(new File(imgFilePath));
           byte[] buf = new byte[8096];
           int size = 0;
           while ((size = bis.read(buf)) != -1)
             fos.write(buf, 0, size);
           fos.close();
           bis.close();

           logger.info("下载媒体文件成功,filePath="+ imgFilePath);
         } catch (Exception e) {
        	 imgFilePath = null;
        	 logger.error("下载媒体文件失败:",e);
         } finally {
        	 if (bis != null) {
        		 try {
        			 bis.close();
        		 } catch (IOException e) {
        			 logger.error("连接微信出错:",e);
        		 }
        	}
        	if (fos != null) {
        	     try {
        	    	 fos.close();
        	     } catch (IOException e) {
        	    	 logger.error("连接微信出错:",e);
        	     }
        	}
        }
		return imgFilePath;
    }

 

HttpClient httpclient = new DefaultHttpClient();
		HttpPost post = new HttpPost(IMAGE_FTP_PATH);
		File file = new File(filePath);
		FileBody fileBody = new FileBody(file);
		try {

			MultipartEntity entity = new MultipartEntity();
			entity.addPart("file", fileBody);
			post.setEntity(entity);
			HttpResponse response = httpclient.execute(post);
			logger.info("图片服务器返回code:" + response.getStatusLine().getStatusCode());
			if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {

				HttpEntity entitys = response.getEntity();
				if (entitys != null) {
					//resultLen = entity.getContentLength();
					returnStr = EntityUtils.toString(entitys);
					
					logger.info("图片服务器返回returnStr:" + returnStr);
				}
			}
			httpclient.getConnectionManager().shutdown();
			
			//删除本地
			//file.delete();
		} catch (UnsupportedEncodingException e) {
			logger.error(e.getMessage(), e);
		} catch (ClientProtocolException e) {
			logger.error(e.getMessage(), e);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}

 

 

3、

 

 

package com.common.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Map;

/** 
 * @author Administrator 
 * 
 */
public class HttpUtils {

	/** 
	 * 使用Get方式获取数据 
	 *  
	 * @param url 
	 *            URL包括参数,http://HOST/XX?XX=XX&XXX=XXX 
	 * @param charset 
	 * @return 
	 */
	public static String sendGet(String url) {
		String result = "";
		BufferedReader in = null;
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接  
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性  
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 建立实际的连接  
			connection.connect();
			// 定义 BufferedReader输入流来读取URL的响应  
			in = new BufferedReader(new InputStreamReader(connection
					.getInputStream(), "utf-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送GET请求出现异常!" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流  
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}

	/**  
	 * POST请求,字符串形式数据  
	 * @param url 请求地址  
	 * @param param 请求数据  
	 * @param charset 编码方式  
	 */
	public static String sendPostUrl(String url, String param, String charset) {

		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接  
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性  
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 发送POST请求必须设置如下两行  
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流  
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数  
			out.print(param);
			// flush输出流的缓冲  
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应  
			in = new BufferedReader(new InputStreamReader(
					conn.getInputStream(), charset));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常!" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流  
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

	/**  
	 * POST请求,Map形式数据  
	 * @param url 请求地址  
	 * @param param 请求数据  
	 * @param charset 编码方式  
	 */
	public static String sendPost(String url, Map param,
			String charset) {

		StringBuffer buffer = new StringBuffer();
		if (param != null && !param.isEmpty()) {
			for (Map.Entry entry : param.entrySet()) {
				buffer.append(entry.getKey()).append("=").append(
						URLEncoder.encode(entry.getValue())).append("&");

			}
		}
		buffer.deleteCharAt(buffer.length() - 1);

		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接  
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性  
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 发送POST请求必须设置如下两行  
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流  
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数  
			out.print(buffer);
			// flush输出流的缓冲  
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应  
			in = new BufferedReader(new InputStreamReader(
					conn.getInputStream(), charset));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常!" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流  
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

	public static void main(String[] args) {
	}
}

 

工具类3:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

public class HttpRequest {
//	private static Logger logger = Logger.getLogger(HttpRequest.class);
    /**
     * 向指定URL发送GET方法的请求
     * 
     * 
     * @param url
     *            发送请求的URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常!" + e);
          //  logger.error("连接出错",e);
        }
        
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
               // logger.error("连接出错",e2);
            }
        }
        return result;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     * 
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            OutputStream outputStream = conn.getOutputStream();
            String aa = new String(param.getBytes("UTF8"),"UTF8");
            System.out.println("=========== "+aa);
            out = new PrintWriter(outputStream);
            // 发送请求参数
            out.print(aa);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!"+e);
            //logger.error("连接出错",e);
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
            	// logger.error("连接出错",ex);
            }
        }
        return result;
    }
    
}

 

工具类4:

 

 

 

  • Http请求工具类HttpUtil_第2张图片
  • 大小: 59.6 KB
  • 查看图片附件

你可能感兴趣的:(Http请求工具类HttpUtil)