向指定URL 發送POST請求的方法

java發送psot請求:java

package com.tea.web.admin;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class PsotTest {
    
    public static void main(String[] args) {
        HashMap<String, Object> params = new HashMap<>();
        params.put("customerType", 2);
        params.put("token", "3d88f30fb4d129027ca5f9c04ed5b733");
        params.put("sign", "94257c28f256fbb66b4efd889d1d09be2");
        String result = sendPost("http://api.teayk.com/sys/api/customerGrade/findGradeByType", params);
        System.err.println(result);
    }
    private static String sendPost(String url, Map<String, Object> params) {
        OutputStreamWriter out = null;
        BufferedReader in = null;        
        StringBuilder result = new StringBuilder(); 
        try {
            HttpURLConnection conn =(HttpURLConnection) new URL(url).openConnection();
            //發送POST請求必須設置以下兩行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");//POST方法
            //設置通用的請求屬性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.connect();
            //獲取URLConnection對象對應的輸出流
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            //發送請求參數            
            if (params != null) {
                 /* 
                  StringBuilder param = new StringBuilder(); 
                  for (Map.Entry<String, String> entry : params.entrySet()) {
                      if(param.length()>0){
                          param.append("&");
                      }                  
                      param.append(entry.getKey());
                      param.append("=");
                      param.append(entry.getValue());                      
                      System.out.println(entry.getKey()+":"+entry.getValue());
                  }
                  System.out.println("param:"+param.toString());
                  out.write(param.toString());
                 */
                
                JSONObject json =(JSONObject) JSON.toJSON(params);
                System.out.println(json);
                out.write(json.toString());
            }
            out.flush();// flush輸出流的緩衝
            // 定義BufferedReader輸入流來讀取URL的響應
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {            
            e.printStackTrace();
        }
        //使用finally塊來關閉輸出流、輸入流
        finally{
            try{
                if(out!=null){ out.close();}
                if(in!=null){in.close();}
            }catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result.toString();
    }
}
相關文章
相關標籤/搜索