Java 發送http post 請求


package com.sm.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.apache.http.NameValuePair;
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.EntityUtils;

public class HttpUtils {
    public static final String CHARSET = "UTF-8";
    // 發送get請求 url?a=x&b=xx形式
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlName = "";
            if (param.length() != 0) {
                urlName = url + "?" + param;
            } else
                urlName = url;
            URL resUrl = new URL(urlName);
            URLConnection urlConnec = resUrl.openConnection();
            urlConnec.setRequestProperty("accept", "*/*");
            urlConnec.setRequestProperty("connection", "Keep-Alive");
            urlConnec.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            urlConnec.connect();
            Map<String, List<String>> map = urlConnec.getHeaderFields();
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定義 BufferedReader輸入流來讀取URL的響應
            in = new BufferedReader(new InputStreamReader(urlConnec.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("發送get請求失敗" + e);
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    // 發送post請求
    public static String sendPost(String url, MultipartHttpServletRequest param) {
        String result = "";
        PrintWriter out = null;
        BufferedReader in = null;
        try {
            URL resUrl = new URL(url);
            URLConnection urlConnec = resUrl.openConnection();
            urlConnec.setRequestProperty("accept", "*/*");
            urlConnec.setRequestProperty("connection", "Keep-Alive");
            urlConnec.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 發送POST請求必須設置如下兩行
            urlConnec.setDoInput(true);
            urlConnec.setDoOutput(true);

            out = new PrintWriter(urlConnec.getOutputStream());
            out.print(param);// 發送post參數
            out.flush();
            // 定義 BufferedReader輸入流來讀取URL的響應
            in = new BufferedReader(new InputStreamReader(urlConnec.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("post請求發送失敗" + e);
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }
    
    
    //post請求方法
    public static  String sendPost(String url, Map<String,Object> params) {
       String response = null;
       System.out.println(url);
       System.out.println(params);
       try {
           List<NameValuePair> pairs = null;
            if (params != null && !params.isEmpty()) {
                pairs = new ArrayList<NameValuePair>(params.size());
                for (String key : params.keySet()) {
                    pairs.add(new BasicNameValuePair(key, params.get(key).toString()));
            }
            }
           CloseableHttpClient httpclient = null;
           CloseableHttpResponse httpresponse = null;
           try {
               httpclient = HttpClients.createDefault();
               HttpPost httppost = new HttpPost(url);
              // StringEntity stringentity = new StringEntity(data);
               if (pairs != null && pairs.size() > 0) {
                   httppost.setEntity(new UrlEncodedFormEntity(pairs, CHARSET));
               }
               httpresponse = httpclient.execute(httppost);
               response = EntityUtils
                       .toString(httpresponse.getEntity());
               System.out.println(response);
           } finally {
               if (httpclient != null) {
                   httpclient.close();
               }
               if (httpresponse != null) {
                   httpresponse.close();
               }
           }
       } catch (Exception e) {
           e.printStackTrace();
       }
       return response;
    }
    public static void main(String[] args) {
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("id","123456666");
        sendPost("http://192.168.1.56:8080/smkj/api/lcds/user/lcdsUser",map);
    }
    /**
     * 測試
     * 說明:這里用新浪股票接口做get測試,新浪股票接口不支持jsonp,至於post,因為本人用的公司的接口就不展示了,一樣的,一個url,一個數據包
     */
    /*
     * public static void main(String[] args) { // TODO Auto-generated method
     * stub String resultGet = sendGet("http://hq.sinajs.cn/list=sh600389","");
     * System.out.println(resultGet); }
     */

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM