HttpURLConnection 的使用:
HttpURLconnection是基於http協議的,支持get,post,put,delete等各種請求方式,最常用的就是get和post
做過微信支付的童鞋應該曉得這個東西.
利用HttpURLconnection去請求接口,從目標接口獲得返回數據.
/**
* 方法內請求接口
*
* @param reqMsg
* @return
* @throws Exception
*/
public Map<String,String> requirest(ISOMsg reqMsg) {
try {
//創建鏈接
URL httpUrl = new URL("http://XXX");
//打開連接
HttpURLConnection Connection = (HttpURLConnection) httpUrl.openConnection();
Connection.setRequestMethod("POST");
// 發送POST請求必須設置如下兩行
Connection.setDoOutput(true);
Connection.setDoInput(true);
}
Connection.connect();
// 獲取URLConnection對象對應的輸出流
PrintWriter printWriter = new PrintWriter(Connection.getOutputStream());
// 發送請求參數
printWriter.write("aa="+aa+"&bb="+bb);//post的參數
// flush輸出流的緩衝
printWriter.flush();
//開始獲取數據
BufferedInputStream bis = new BufferedInputStream(Connection.getInputStream());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int len;
byte[] arr = new byte[1024];
while((len=bis.read(arr))!= -1){
bos.write(arr,0,len);
bos.flush();
bos.close();
String date = bos.toString("utf-8");//返回
log.info("返回數據:"+date);
//轉成json
Object json =JSON.parse(date);
//json轉map
Map<String,String> map = (Map)json;
} catch (Exception e) {
e.printStackTrace();
}
return reqMsg;
}