Java利用原始HttpURLConnection请求网络数据 package com.util;import java.io.*;import java.net.HttpURLConnection;import java.net.URL;import java.util.HashMap;import java.util.Map;/** * Created by Administrator on 2017/11/1 0001. */pu
package com.util;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Administrator on 2017/11/1 0001.
*/
public class httpURLConnectionUtils {
private static int BUFFER_SIZE = 10240;
public final static boolean DEBUG = true; // 调试用
/**
* 获取字符串 get
* @param destUrl
* @return
*/
public static String httpGetRequest(String destUrl) {
try {
// 1. 得到访问地址的URL
URL url = new URL(destUrl);
// 2. 得到网络访问对象java.net.HttpURLConnection
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
/* 3. 设置请求参数(过期时间,输入、输出流、访问方式),以流的形式进行连接 */
// 设置是否向HttpURLConnection输出
connection.setDoOutput(false);
// 设置是否从httpUrlConnection读入
connection.setDoInput(true);
// 设置请求方式
connection.setRequestMethod("GET");
// 设置是否使用缓存
connection.setUseCaches(true);
// 设置此 HttpURLConnection 实例是否应该自动执行 HTTP 重定向
connection.setInstanceFollowRedirects(true);
// 设置超时时间
connection.setConnectTimeout(3000);
// 连接
connection.connect();
// 4. 得到响应状态码的返回值 responseCode
int code = connection.getResponseCode();
// 5. 如果返回值正常,数据在网络中是以流的形式得到服务端返回的数据
String msg = "";
if (code == 200) { // 正常响应
// 从流中读取响应信息
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) { // 循环从流中读取
msg += line + "\n";
}
reader.close(); // 关闭流
}
// 6. 断开连接,释放资源
connection.disconnect();
// 显示响应结果
//System.out.println(msg);
return msg;
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
/**
* 获取文件流 get
* @param destUrl
* @param fileName
* @return
*/
public static int httpGetRequest(String destUrl,String fileName) {
FileOutputStream fos = null;
BufferedInputStream bis = null;
HttpURLConnection httpUrl = null;
URL url = null;
byte[] buf = new byte[BUFFER_SIZE];
int size = 0;
try {
// 建立链接
url = new URL(destUrl);
httpUrl = (HttpURLConnection) url.openConnection();
// 连接指定的资源
httpUrl.connect();
// 获取网络输入流
bis = new BufferedInputStream(httpUrl.getInputStream());
// 建立文件
fos = new FileOutputStream(fileName);
if (DEBUG)
System.out.println("正在获取链接[" + destUrl + "]的内容...\n将其保存为文件["+ fileName + "]");
// 保存文件
while ((size = bis.read(buf)) != -1)
fos.write(buf, 0, size);
fos.close();
bis.close();
httpUrl.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
return 1;
}
public static String httpPoetRequest(String destUrl,Map
params) {
URL url = null;
StringBuffer paramsStr = new StringBuffer();
for (Map.Entry
param : params.entrySet()) { paramsStr.append(param.getKey()); paramsStr.append("&"); paramsStr.append(String.valueOf(param.getValue())); } try { url = new URL(destUrl); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod("POST");// 提交模式 // conn.setConnectTimeout(10000);//连接超时 单位毫秒 // conn.setReadTimeout(2000);//读取超时 单位毫秒 // 发送POST请求必须设置如下两行 httpURLConnection.setDoOutput(true); httpURLConnection.setDoInput(true); // 获取URLConnection对象对应的输出流 PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream()); // 发送请求参数 printWriter.write(paramsStr.toString());//post的参数 xx=xx&yy=yy // flush输出流的缓冲 printWriter.flush(); //开始获取数据 BufferedInputStream bis = new BufferedInputStream(httpURLConnection.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(); return bos.toString("utf-8"); } catch (Exception e) { e.printStackTrace(); } return ""; } /** * 获取文件流 Poet * @param destUrl * @param fileName * @return */ public static int httpPoetRequest(String destUrl,Map
params,String fileName) { FileOutputStream fos = null; BufferedInputStream bis = null; URL url = null; byte[] buf = new byte[BUFFER_SIZE]; int size = 0; StringBuffer paramsStr = new StringBuffer(); for (Map.Entry
param : params.entrySet()) { paramsStr.append(param.getKey()); paramsStr.append("&"); paramsStr.append(String.valueOf(param.getValue())); } try { url = new URL(destUrl); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setDoOutput(true); httpURLConnection.setDoInput(true); // 获取URLConnection对象对应的输出流 PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream()); // 发送请求参数 printWriter.write(paramsStr.toString());//post的参数 xx=xx&yy=yy // flush输出流的缓冲 printWriter.flush(); //开始获取数据 bis = new BufferedInputStream(httpURLConnection.getInputStream()); // 建立文件 fos = new FileOutputStream(fileName); if (DEBUG) System.out.println("正在获取链接[" + destUrl + "]的内容...\n将其保存为文件["+ fileName + "]"); // 保存文件 while ((size = bis.read(buf)) != -1) fos.write(buf, 0, size); fos.close(); bis.close(); httpURLConnection.disconnect(); } catch (Exception e) { e.printStackTrace(); } return 1; } public static void main(String[] args) { String destUrl = "http://localhost:8075/WebReport/ReportServer?reportlet=WorkBook1.cpt&format=pdf&aa=12"; String fileName = "D:/aa.pdf"; // int i = httpURLConnectionUtils.httpGetRequest(destUrl, fileName); Map
map = new HashMap
(); map.put("aa","qwe"); int s = httpURLConnectionUtils.httpPoetRequest(destUrl,map,fileName); System.out.println("httpURLConnectionUtils.httpGetRequest:"+s); } }
