对账单文件下载 GTE,POST都可以注意参数区分
注意微信下载是没有格式的文件注意文件改成txt格式或者直接用notepad++打开
public static void main(String[] arg) {
downloadFile(wxUrl, "D:/test/WX/****.gzip", reuqestXml, "POST");
}
/**
*
* @param urlPath 请求地址
* @param saveUrl 保存文件地址
* @param data 请求参数
* @param status 请求类型 post get
* @return
* @throws IOException
* @throws Exception
*/
public static void downloadFile(String urlPath, String saveUrl, String data,String status) {
// 设置访问地址
URL url = null;
HttpURLConnection httpURLConnection = null;
InputStream inputStream = null;
FileOutputStream fos = null;
try {
url = new URL(urlPath);
// http的连接类 得到网络访问对象
httpURLConnection = (HttpURLConnection) url.openConnection();
// 设置请求参数(访问方式,超时时间,输入,输出流,请求头信息),以流的形式进行连接
// 设定请求的方法,默认是GET
httpURLConnection.setRequestMethod(status);
// 超时时间
httpURLConnection.setConnectTimeout(5000);
// 设置是否向HttpURLConnection输出
httpURLConnection.setDoOutput(true);
// 设置是否从httpUrlConnection读入
httpURLConnection.setDoInput(true);
// 设置使用编码格式参数的名-值对
httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
httpURLConnection.setRequestProperty("Charsert", "UTF-8");
// 简历连接
httpURLConnection.connect();
if(data!=null&&data!=""){
// 写入参数到请求中
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(httpURLConnection.getOutputStream(),
"UTF-8"));
// 传递参数
writer.write(data.toString());
writer.flush();
writer.close();
}
// 获取响应code 200成功
int code = httpURLConnection.getResponseCode();
if (code == 200) {
inputStream = httpURLConnection.getInputStream();
// 判断字节大小
if (inputStream.available() != 0) {
System.out.println("结果大小:" + inputStream.available());
File file = new File(saveUrl);
if (!file.getParentFile().exists()) {
boolean result = file.getParentFile().mkdirs();
if (!result) {
System.out.println("创建失败");
}
}
byte[] temp = new byte[1024];
int b;
fos = new FileOutputStream(file);
while ((b = inputStream.read(temp)) != -1) {
fos.write(temp, 0, b);
fos.flush();
}
}
}
// 关闭 http连接,释放资源
httpURLConnection.disconnect();
}
catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
//最终都执行关流
try {
if (inputStream != null)
inputStream.close();
if (fos != null)
fos.close();
if (httpURLConnection != null)
httpURLConnection.disconnect();
}
catch (IOException e) {
e.printStackTrace();
}
}
}