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;
}