post和get請求調用Http接口並拿到數據

下面介紹幾種調用HTTP接口拿到返回值的方法
第一種採用post請求調用接口
/**
* 發送Http post請求
*
* @param jsonInfo
* 調用接口所傳的參數
* @param URL
* 請求url
* @return ResponseString
* 拿到的返回信息
* @throws Exception
*/
public static String doHttpPost(String URL,JSONObject jsonInfo) throws Exception {
System.out.println(“登錄接口發起的數據:” + jsonInfo);

    InputStream instr = null;
    try {
        byte[] jsonData = jsonInfo.toString().getBytes("utf-8");
        URL url = new URL(URL);
        URLConnection urlCon = url.openConnection();
        urlCon.setDoOutput(true);//可以發生信息到URLConnection
        urlCon.setDoInput(true);//可以接受來自URLConnection的輸入
        urlCon.setUseCaches(false);
        urlCon.setRequestProperty("content-Type", "application/json");//設置請求頭
        urlCon.setRequestProperty("charset", "utf-8");
        urlCon.setRequestProperty("Content-length",String.valueOf(jsonData.length));
       logger.debug("登錄接口所傳參數長度:"+String.valueOf(jsonData.length));
        DataOutputStream printout = new DataOutputStream(urlCon.getOutputStream());
        printout.write(jsonData);
        printout.flush();
        printout.close();
        instr = urlCon.getInputStream();
        byte[] bis = IOUtils.toByteArray(instr);
        String ResponseString = new String(bis, "UTF-8");
        if ((ResponseString == null) || ("".equals(ResponseString.trim()))) {
            logger.debug("登陸接口返回空");
        }
        logger.debug("登錄接口返回數據爲:" + ResponseString);
        return ResponseString;

    } catch (Exception e) {
        logger.debug("登錄接口發送的地址=" + URL + "登錄接口發送的數據:" + jsonInfo + "登錄接口發送數據失敗:" + e.getMessage());
        throw new Exception( e.getMessage());
    } finally {
        try {
            instr.close();

        } catch (Exception ex) {
            return "0";
        }
    }
}

第二種採用get請求調用接口
/**
* 向指定URL發送GET方法的請求
*
* @param url
* 發送請求的URL
* @param param
* 請求參數,請求參數應該是 name1=value1&name2=value2 的形式。
* @return URL
* 所代表遠程資源的響應結果
*/
public static String sendGet(String url, String param) {
String result = “”;
BufferedReader in = null;
try {
String urlNameString = “http://”+url + “?” + param;
System.out.println(urlNameString);
URL realUrl = new URL(urlNameString);
// 打開和URL之間的連接
URLConnection connection = realUrl.openConnection();
// 設置通用的請求屬性
connection.setRequestProperty(“accept”, “/“);
connection.setRequestProperty(“connection”, “Keep-Alive”);
connection.setRequestProperty(“user-agent”,
“Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)”);
// 建立實際的連接
connection.connect();
// 獲取所有響應頭字段
Map

發佈了32 篇原創文章 · 獲贊 14 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章