Java實現HttpGet和HttpPost請求


maven引入JSON處理jar

   <dependency>
	   <groupId>com.alibaba</groupId>
	   <artifactId>fastjson</artifactId>
	   <version>1.2.58</version>
   </dependency>

maven引入數據源配置,用於log記錄

   <dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>druid</artifactId>
	<version>1.1.0</version>
   </dependency>

HttpGet和HttpPost請求


import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.SQLOutput;
import java.util.Map;

public class ReqHttp {

    private static final Log logger = LogFactory.getLog(ReqHttp.class);

    public static JSONObject get(String reqUrl,Map<String,Object> paramMap) throws IOException {

        StringBuffer param =new StringBuffer();

        for(Map.Entry<String,Object> en:paramMap.entrySet()){
            param.append(en.getKey()+"="+en.getValue()+"&");
        }

        BufferedReader responseReader = null;

        String urlPath = ReqStatUrl.DOMAIN_URL + reqUrl+"?"+param.toString();
        try {
            //建立連接
            URL url = new URL(urlPath);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            //設置參數
            httpConn.setDoOutput(true);   //需要輸出
            httpConn.setDoInput(true);   //需要輸入
            httpConn.setUseCaches(false);  //不允許緩存
            httpConn.setRequestMethod("GET");   //設置GET方式連接
            httpConn.setRequestProperty("Content-Type", "application/json;charset=utf-8");//流信息 可以傳輸圖片音頻等信息
            httpConn.setRequestProperty("Charset", "UTF-8");
            httpConn.setRequestProperty("entCode", ReqStatHeader.entCode);//參數常量
            httpConn.setRequestProperty("tokenId", ReqStatHeader.tokenId);//參數常量
            httpConn.setConnectTimeout(30000);
            httpConn.setReadTimeout(30000);

            //連接,也可以不用明文connect,使用下面的httpConn.getOutputStream()會自動connect
            httpConn.connect();

            //獲得響應狀態
            int resultCode = httpConn.getResponseCode();
            if (HttpURLConnection.HTTP_OK == resultCode) {
                StringBuffer sb = new StringBuffer();
                String readLine = new String();
                responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
                while ((readLine = responseReader.readLine()) != null) {
                    sb.append(readLine).append("\n");
                }

                System.out.println(sb.toString());
                logger.info(sb.toString());
                JSONObject json = JSONObject.parseObject(sb.toString(),JSONObject.class);
                return json;
            }


        } catch (Exception e) {
            logger.error("get 請求失敗:"+urlPath);
        } finally {

            if(null != responseReader) responseReader.close();

        }
        return null;
    }



    public static JSONObject post(String reqUrl,Map<String,Object> paramMap) throws Exception {

        BufferedReader responseReader = null;
        OutputStream dos= null;

        String urlPath = ReqStatUrl.DOMAIN_URL + reqUrl;
        try {
            //建立連接
            URL url = new URL(urlPath);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            //設置參數
            httpConn.setDoOutput(true);   //需要輸出
            httpConn.setDoInput(true);   //需要輸入
            httpConn.setUseCaches(false);  //不允許緩存
            httpConn.setRequestMethod("POST");   //設置POST方式連接
            httpConn.setRequestProperty("Content-Type", "application/json;charset=utf-8");//流信息 可以傳輸圖片音頻等信息
            httpConn.setRequestProperty("Charset", "UTF-8");
            httpConn.setRequestProperty("entCode", ReqStatHeader.entCode);//參數常量
            httpConn.setRequestProperty("tokenId", ReqStatHeader.tokenId);//參數常量
            httpConn.setConnectTimeout(30000);
            httpConn.setReadTimeout(30000);

            //連接,也可以不用明文connect,使用下面的httpConn.getOutputStream()會自動connect
            httpConn.connect();
            //建立輸入流,向指向的URL傳入參數

            byte[] jsonObject = JSONObject.toJSONBytes(paramMap);

            dos = httpConn.getOutputStream();
            dos.write(jsonObject);
            dos.flush();

            //獲得響應狀態
            int resultCode = httpConn.getResponseCode();
            if (HttpURLConnection.HTTP_OK == resultCode) {
                StringBuffer sb = new StringBuffer();
                String readLine = new String();
                responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
                while ((readLine = responseReader.readLine()) != null) {
                    sb.append(readLine).append("\n");
                }

//                System.out.println(sb.toString());
                logger.info(sb.toString());
                JSONObject json = JSONObject.parseObject(sb.toString(),JSONObject.class);
                return json;
            }


        } catch (Exception e) {
            logger.error("get 請求失敗:"+urlPath);
        } finally {

            if(null != responseReader) responseReader.close();
            if(null != dos) dos.close();
        }
        return null;
    }


}

常用參數靜態引用

public class ReqStatHeader {

    public static String entCode="";
    public static String tokenId="";

    public static  String appCode = "";
    public static  String secret = "";

}

常用API地址靜態引用,便於地址維護

public class ReqStatUrl {

    public static String DOMAIN_URL = "https://www.xxxxx.com/xxxx/xxxx";

    /**
     * 認證
     */
    public static String AUTH_LOGIN = "/auth/login";

    /**
     *獲取已提交對私報銷單據
     */
    public static String REPORT_PERSONAL_SUBMITTED=  "/report/personal/submitted";

    /**
     * 獲取已提交對私報銷單據詳情
     */
    public static String  REPORT_PERSONAL_DETAIL = "/report/personal/detail";


}


免責聲明!

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



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