1. 程式人生 > >Http Post請求與解析

Http Post請求與解析

1.所需jar
<!-- 格式化物件,方便輸出日誌 -->  
 <dependency>  
    <groupId>com.alibaba</groupId>  
     <artifactId>fastjson</artifactId>  
     <version>1.1.41</version>  
</dependency> 
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
   <dependency>
       <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
         <version>4.5.1</version>
    </dependency> 
2.post請求
package com.*.springmvc.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;

public class HttpPost {

    public static String sendPost(String url, Map<String, String> paramMap) {  
        PrintWriter out = null;  
        BufferedReader in = null;  
        String result = "";  
        try {  
            URL realUrl = new 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)");  
            conn.setDoOutput(true);  
            conn.setDoInput(true);  
            out = new PrintWriter(conn.getOutputStream());  
 
            String param = "";  
            if (paramMap != null && paramMap.size() > 0) {  
                Iterator<String> ite = paramMap.keySet().iterator();  
                while (ite.hasNext()) {  
                    String key = ite.next();// key  
                    String value = paramMap.get(key);  
                    param += key + "=" + value + "&";  
                }  
                param = param.substring(0, param.length() - 1);  
            }  
 
            out.print(param);  
            out.flush();  
            in = new BufferedReader(  
                    new InputStreamReader(conn.getInputStream()));  
            String line;  
            while ((line = in.readLine()) != null) {  
                result += line;  
            }  
        } catch (Exception e) {  
            System.err.println(e);  
            e.printStackTrace();  
        }  
        finally {  
            try {  
                if (out != null) {  
                    out.close();  
                }  
                if (in != null) {  
                    in.close();  
                }  
            } catch (IOException ex) {  
                ex.printStackTrace();  
            }  
        }  
        return result;  
    }  
      

    public static String doPost(String urlStr, String strInfo) {  
        String reStr="";  
        try {  
            URL url = new URL(urlStr);  
            URLConnection con = url.openConnection();  
            con.setDoOutput(true);  
            con.setRequestProperty("Pragma:", "no-cache");  
            con.setRequestProperty("Cache-Control", "no-cache");  
            con.setRequestProperty("Content-Type", "text/xml");  
            OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());  
            out.write(new String(strInfo.getBytes("utf-8")));  
            out.flush();  
            out.close();  
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));  
            String line = "";  
            for (line = br.readLine(); line != null; line = br.readLine()) {  
                reStr += line;  
            }  
        } catch (MalformedURLException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        return reStr;  
    }  
     
    public static void main(String[] args) {  
        Map<String, String> mapParam = new HashMap<String, String>();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("pageSize", "1");
        jsonObject.put("PageNum","10");
        mapParam.put("pageSize", "1");
        mapParam.put("PageNum","10");
        String pathUrl = "http://*.*.*.*:port/xxxx/xxxx";  
        String result = sendPost1(pathUrl, jsonObject);  
        System.out.println(result); 
    }  
    
    public static String sendPost1(String url, JSONObject jsonObject) {  
        PrintWriter out = null;  
        BufferedReader in = null;  
        String result = "";  
        try {  
            URL realUrl = new 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)");  
            conn.setDoOutput(true);  
            conn.setDoInput(true);  
            out = new PrintWriter(conn.getOutputStream());  

            out.print(jsonObject);  
            out.flush();  
            in = new BufferedReader(  
                    new InputStreamReader(conn.getInputStream()));  
            String line;  
            while ((line = in.readLine()) != null) {  
                result += line;  
            }  
        } catch (Exception e) {  
            System.err.println(e);  
            e.printStackTrace();  
        }  
        finally {  
            try {  
                if (out != null) {  
                    out.close();  
                }  
                if (in != null) {  
                    in.close();  
                }  
            } catch (IOException ex) {  
                ex.printStackTrace();  
            }  
        }  
        return result;  
    }
}
3.請求
    @RequestMapping("/xxxx/xxxx")
    @ResponseBody
    public JSONObject getItemList1(HttpServletRequest request) throws IOException {
        ServletInputStream inputStream = null;
        String param;
        try {
            inputStream = request.getInputStream();
            param = IOUtils.toString(inputStream);
            System.out.println(param);
            JSONObject json = null;
            EasyUIDataGridResult list = null;
            try {
                json = JSON.parseObject(param);
                Integer page = Integer.parseInt(json.getString("pageSize"));
                Integer rows = Integer.parseInt(json.getString("PageNum"));
                list = itemService.getItenList(page, rows);
            } catch (Exception e) {
                JSONObject returnJson = new JSONObject();
                returnJson.put("DATA", null);
                returnJson.put("STATUS", "ERROR");
                returnJson.put("MSG", "引數名與條件不符");
            }
            JSONObject returnJson = new JSONObject();
            returnJson.put("DATA", list);
            returnJson.put("STATUS", "SUCCESS");
            returnJson.put("MSG", "SUCCESS");
            inputStream.close();
            return returnJson;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            inputStream.close();
            JSONObject returnJson = new JSONObject();
            returnJson.put("DATA", null);
            returnJson.put("STATUS", "ERROR");
            returnJson.put("MSG", "IO異常");
            return null;
        }

    }
4.返回結果
{"MSG":"SUCCESS","STATUS":"SUCCESS","DATA":{"total":934,"rows":[{"id":536563,"title":"new2 - 阿爾卡特 (OT-927) 炭黑 聯通3G手機 雙卡雙待","sellPoint":"清倉!僅北京,武漢倉有貨!","price":29900000,"num":99999,"barcode":"","image":"http://image.e3mall.cn/jd/4ef8861cf6854de9889f3db9b24dc371.jpg","cid":560,"status":1,"created":1425821598000,"updated":1428755918000},]}}