java中发送http请求的方法

package org.jeecgframework.test.demo;
import java.io.BufferedReader;
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.io.InputStream;  
import java.io.InputStreamReader;  
import java.io.OutputStream;
import java.io.OutputStreamWriter;  
import java.io.UnsupportedEncodingException;  
import java.net.ConnectException;
import java.net.HttpURLConnection;  
import java.net.Socket;  
import java.net.URL;  
import java.net.URLConnection;  
import java.net.URLEncoder;  
import java.util.ArrayList;  
import java.util.HashMap;  
import java.util.Iterator;  
import java.util.List;  
import java.util.Map;  
import java.util.Map.Entry;  
 



import java.util.Set;
import java.util.SortedMap;

import org.apache.http.HttpResponse;  
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;  


 

public class HttpClientHelper {  
    /**
     * @Description:使用HttpURLConnection发送post请求
     * @author:liuyc
     * @time:2016年5月17日 下午3:26:07
     */  
    public static String sendPost(String urlParam, Map<String, Object> params, String charset) {  
        StringBuffer resultBuffer = null;  
        // 构建请求参数  
        StringBuffer sbParams = new StringBuffer();  
        if (params != null && params.size() > 0) {  
            for (Entry<String, Object> e : params.entrySet()) {  
                sbParams.append(e.getKey());  
                sbParams.append("=");  
                sbParams.append(e.getValue());  
                sbParams.append("&");  
            }  
        }  
        HttpURLConnection con = null;  
        OutputStreamWriter osw = null;  
        BufferedReader br = null;  
        // 发送请求  
        try {  
            URL url = new URL(urlParam);  
            con = (HttpURLConnection) url.openConnection();  
            con.setRequestMethod("POST");  
            con.setDoOutput(true);  
            con.setDoInput(true);  
            con.setUseCaches(false);  
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");  
            if (sbParams != null && sbParams.length() > 0) {  
                osw = new OutputStreamWriter(con.getOutputStream(), charset);  
                osw.write(sbParams.substring(0, sbParams.length() - 1));  
                osw.flush();  
            }  
            // 读取返回内容  
            resultBuffer = new StringBuffer();  
            int contentLength = Integer.parseInt(con.getHeaderField("Content-Length"));  
            if (contentLength > 0) {  
                br = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));  
                String temp;  
                while ((temp = br.readLine()) != null) {  
                    resultBuffer.append(temp);  
                }  
            }  
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        } finally {  
            if (osw != null) {  
                try {  
                    osw.close();  
                } catch (IOException e) {  
                    osw = null;  
                    throw new RuntimeException(e);  
                } finally {  
                    if (con != null) {  
                        con.disconnect();  
                        con = null;  
                    }  
                }  
            }  
            if (br != null) {  
                try {  
                    br.close();  
                } catch (IOException e) {  
                    br = null;  
                    throw new RuntimeException(e);  
                } finally {  
                    if (con != null) {  
                        con.disconnect();  
                        con = null;  
                    }  
                }  
            }  
        }  
 
        return resultBuffer.toString();  
    }  
 
   
    /**  
     * @Description:使用HttpClient发送post请求  
     * @author:liuyc  
     * @time:2016年5月17日 下午3:28:23  
     */  
    public static String httpClientPost(String urlParam, Map<String, Object> params, String charset) {  
        StringBuffer resultBuffer = null;  
        HttpClient client = new DefaultHttpClient();  
        HttpPost httpPost = new HttpPost(urlParam);  
        // 构建请求参数  
        List<NameValuePair> list = new ArrayList<NameValuePair>();  
        Iterator<Entry<String, Object>> iterator = params.entrySet().iterator();  
        while (iterator.hasNext()) {  
            Entry<String, Object> elem = iterator.next();  
            list.add(new BasicNameValuePair(elem.getKey(), String.valueOf(elem.getValue())));  
        }  
        BufferedReader br = null;  
        try {  
            if (list.size() > 0) {  
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);  
                httpPost.setEntity(entity);
            }  
            HttpResponse response = client.execute(httpPost);  
            // 读取服务器响应数据  
            resultBuffer = new StringBuffer();  
            br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));  
            String temp;  
            while ((temp = br.readLine()) != null) {  
                resultBuffer.append(temp);  
            }  
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        } finally {  
            if (br != null) {  
                try {  
                    br.close();  
                } catch (IOException e) {  
                    br = null;  
                    throw new RuntimeException(e);  
                }  
            }  
        }  
        return resultBuffer.toString();  
    }  
 
    //请求xml组装  
    public static String getRequestXml(SortedMap<String,Object> parameters){  
          StringBuffer sb = new StringBuffer();  
          sb.append("<xml>");  
          Set es = parameters.entrySet();  
          Iterator it = es.iterator();  
          while(it.hasNext()) {  
              Map.Entry entry = (Map.Entry)it.next();  
              String key = (String)entry.getKey();  
              String value = (String)entry.getValue();  
              if ("attach".equalsIgnoreCase(key)||"body".equalsIgnoreCase(key)||"sign".equalsIgnoreCase(key)) {  
                  sb.append("<"+key+">"+"<![CDATA["+value+"]]></"+key+">");  
              }else {  
                  sb.append("<"+key+">"+value+"</"+key+">");  
              }  
          }  
          sb.append("</xml>");  
          return sb.toString();  
      }  
    //生成签名  
    public static String createSign(String characterEncoding,SortedMap<String,Object> parameters){  
          StringBuffer sb = new StringBuffer();  
          Set es = parameters.entrySet();  
          Iterator it = es.iterator();  
          while(it.hasNext()) {  
              Map.Entry entry = (Map.Entry)it.next();  
              String k = (String)entry.getKey();  
              Object v = entry.getValue();  
              if(null != v && !"".equals(v)  
                      && !"sign".equals(k) && !"key".equals(k)) {  
                  sb.append(k + "=" + v + "&");  
              }  
          }  
          sb.append("key=" + "");  
          String sign = MD5.md5(sb.toString()).toUpperCase();  
          return sign;  
      }  
    //请求方法  
    public static String httpsRequest(String requestUrl, String requestMethod, String data) {  
          try {  
               
              URL url = new URL(requestUrl);  
              HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
              
              conn.setDoOutput(true);  
              conn.setDoInput(true);  
              conn.setUseCaches(false);  
              // 设置请求方式(GET/POST)  
              conn.setRequestMethod(requestMethod);  
              conn.setRequestProperty("content-type", "application/json");
             // conn.setRequestProperty("content-type", "text/xml;charset=utf-8");
              // 当outputStr不为null时向输出流写数据  
              if (null != data) {  
                  OutputStream outputStream = conn.getOutputStream();  
                  // 注意编码格式  
                  outputStream.write(data.getBytes("UTF-8"));  
                  outputStream.close();  
              }  
              // 从输入流读取返回内容  
              InputStream inputStream = conn.getInputStream();  
              InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");  
              BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  
              String str = null;  
              StringBuffer buffer = new StringBuffer();  
              while ((str = bufferedReader.readLine()) != null) {  
                  buffer.append(str);  
              }  
              // 释放资源  
              bufferedReader.close();  
              inputStreamReader.close();  
              inputStream.close();  
              inputStream = null;  
              conn.disconnect();  
              return buffer.toString();  
          } catch (ConnectException ce) {  
              System.out.println("连接超时:{}"+ ce);  
          } catch (Exception e) {  
              System.out.println("https请求异常:{}"+ e);  
          }  
          return null;  
      }
    public static void main(String[] args) {
        String requestUrl,requestMethod,outputStr;
        requestUrl="(此处填写你要请求的url地址)";
        requestMethod="POST";
        outputStr="<xml>"+
                    "<appid><![CDATA[wx2421b1c4370ec43b]]></appid>"+
                    "<mch_id><![CDATA[10000100]]></mch_id>"+
                    "<device_info><![CDATA[1]]></device_info>"+
                    "<nonce_str><![CDATA[5d2b6c2a8db53831f7eda20af46e531c]]></nonce_str>"+
                    "<sign><![CDATA[6245928B869A39BC75A421200A74002E]]></sign>"+
                    "<result_code><![CDATA[SUCCESS]]></result_code>"+
                    "<return_code><![CDATA[SUCCESS]]></return_code>"+
                    "<err_code><![CDATA[1004400740201409030005092168]]></err_code>"+
                    "<err_code_des><![CDATA[1004400740201409030005092168]]></err_code_des>"+
                    "<openid><![CDATA[oUpF8uMEb4qRXf22hE3X68TekukE]]></openid>"+
                    "<is_subscribe><![CDATA[Y]]></is_subscribe>"+
                    "<trade_type><![CDATA[JSAPI]]></trade_type>"+
                    "<bank_type><![CDATA[CFT]]></bank_type>"+
                    "<total_fee><![CDATA[1]]></total_fee>"+
                    "<fee_type><![CDATA[CNY]]></fee_type>"+
                    "<cash_fee><![CDATA[168]]></cash_fee>"+
                    "<cash_fee_type><![CDATA[1004400740201409030005092168]]></cash_fee_type>"+
                    "<transaction_id><![CDATA[1004400740201409030005092168]]></transaction_id>"+
                    "<out_trade_no><![CDATA[137999992017032919767558710]]></out_trade_no>"+
                    "<time_end><![CDATA[20140903131540]]></time_end>"+
                    "<trade_state><![CDATA[1]]></trade_state>"+
                    "<attach><![CDATA[支付测试]]></attach>"+
                    "</xml>";

    //错误的json请求
        // String data = "[{\"id\":1,\"name\":\"o2o_V3.0新版发布\",\"content\":\"o2o_V3.0新版发布\",\"time\":\"2015-05-11 03:12:51\"}]";
        String data = "{\"id\":1,\"name\":\"o2o_V3.0新版发布\",\"content\":\"o2o_V3.0新版发布\",\"time\":\"2015-05-11 03:12:51\"}";
        String xml=httpsRequest(requestUrl,requestMethod,data);
        System.out.println(xml);
        //System.out.println(outputStr);
    }
      
}  

请求的时候只需要调用这个类中的httpsRequest方法,requestUrl代表的就是请求的url地址,requestMethod代表的是以Post或者Get方法请求方式,data就是请求的参数;

posted @ 2017-04-28 20:40  Ocean丶  阅读(916)  评论(0编辑  收藏  举报