import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
public class TestHttpRequest {
/**
* @Description 向指定URL发送GET方法的请求
* @param url 发送请求的url
* @param params 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return url所代表远程资源的响应结果
*/
public static String sendGet(String url, String params) {
StringBuilder result = new StringBuilder();
BufferedReader reader = null;
try {
String urlWithParam = url + "?" + params;
URL realURL = new URL(urlWithParam);
// 建立与url引用的远程对象的连接
URLConnection connection = realURL.openConnection();
// 设置通用请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/5.0 " +
"(Windows NT6.1; WOW64; rv:13.0) Gecko 20100101 Firefox/13.0.1");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map <String, List <String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.out.println(key + "-->" + map.get(key));
}
// 定义BufferedReader输入流来读取URL的响应
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder sb = new StringBuilder("");
while((line = reader.readLine()) != null){
sb.append(line.trim());
}
} catch (MalformedURLException e) {
System.out.println("URL异常");
e.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (reader != null){
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result.toString();
}
复制代码
/**
* @Description 向指定URL发送POST方法的请求
* @param url
* @param params
* @return
*/
public static String sendPost(String url, String params){
StringBuilder result = new StringBuilder();
// PrintWriter以字符为单位,支持汉字;处理人要看得懂的东西就用PrintWriter
PrintWriter out = null;
// OutputStreamWriter以字节为单位,不支持汉字;处理机器看的东西就用OutputStreamWriter,二进制
OutputStreamWriter out2 = null;
BufferedReader in = null;
try {
URL realURL = new URL(url);
// 打开和URL之间的连接
HttpURLConnection connection = (HttpURLConnection)realURL.openConnection();
// 发送POST请求必须设置如下两行
connection.setDoOutput(true);
connection.setDoInput(true);
// 参数长度太大,不能用get方式
connection.setRequestMethod("POST");
// 不适用缓存
connection.setUseCaches(false);
// 设置通用的请求属性
connection.setRequestProperty("Accept", "*/*");
connection.setRequestProperty("Charset", "UTF-8");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/5.0 " +
"(Windows NT6.1; WOW64; rv:13.0) Gecko 20100101 Firefox/13.0.1");
String BOUNDARY = "----------" + System.currentTimeMillis();
connection.setRequestProperty("Content-Type", "multipart/form-data;" +
" boundary=" + BOUNDARY);
//connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// TODO 建立实际的连接
//connection.connect();
// 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,
// 要注意的是connection.getOutputStream会隐含的进行connect。
// 实际上只是建立了一个与服务器的tcp连接,并没有实际发送http请求。
// 获取URLConnection对象对应的输出流
out = new PrintWriter(connection.getOutputStream());
// 发送请求参数
out.print(params);
// flush输出流的缓冲
out.flush();
/*out2 = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
out2.write(params);
out2.flush();*/
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while((line = in.readLine()) != null){
result.append(line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
} finally {
if(out != null){
out.close();
}
try {
/*if( out2 != null){
out2.close();
}*/
if( in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result.toString();
}
}
复制代码
package com.hikvision.util;
import com.alibaba.fastjson.JSONObject;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
public class HttpUtil2 {
private static final String METHOD_POST = "POST";
private static final String METHOD_GET = "GET";
/**
* 发送GET请求
* @param requestURL
* @param param
* @return
*/
public static JSONObject doGet(String requestURL, final String param){
JSONObject response = new JSONObject();
HttpURLConnection conn = null;
try {
requestURL += "?" + param;
conn = getHttpURLConnection(requestURL, METHOD_GET);
conn.connect();
response = readResult(new BufferedReader(new InputStreamReader(conn.getInputStream())));
} catch (IOException e) {
e.printStackTrace();
} finally {
if(conn != null){
conn.disconnect();
}
}
return response;
}
/**
* 发送POST请求
* @param requestURL
* @param jsonObject
* @return
*/
public static JSONObject doPost(final String requestURL, final JSONObject jsonObject){
JSONObject response = new JSONObject();
HttpURLConnection conn = null;
try {
conn = getHttpURLConnection(requestURL, METHOD_POST);
conn.connect();
// printParam(new PrintWriter(conn.getOutputStream()), jsonObject);
writeParam(new DataOutputStream(conn.getOutputStream()), jsonObject);
response = readResult(new BufferedReader(new InputStreamReader(conn.getInputStream())));
} catch (IOException e) {
e.printStackTrace();
} finally {
if(conn != null){
conn.disconnect();
}
}
return response;
}
/**
* 根据指定url和方法获取HttpURLConnection
* @param url
* @param method 指定方法类型(GET,POST,PUT,etc.)
* @return
* @throws IOException
*/
public static HttpURLConnection getHttpURLConnection(final String url, final String method)
throws IOException {
HttpURLConnection conn = (HttpURLConnection)getURLConnection(url);
conn.setRequestMethod(method);
conn.setInstanceFollowRedirects(true);
// 应用程序将从URL连接读取数据,
// 因为总是使用conn.getInputStream()获取服务端的响应,因此默认值是true
if(METHOD_POST.equals(method)){
// get请求用不到conn.getOutputStream(),因为参数默认追加在url后面,因此默认false
conn.setDoOutput(true);
}
return conn;
}
/**
* 根据指定url获取URLConnection
* @param url
* @return
* @throws IOException
*/
public static URLConnection getURLConnection(final String url) throws IOException{
URL realURL = new URL(url);
URLConnection conn = realURL.openConnection();
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
// 连接建立超时时间还有读取数据超时时间,
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
return conn;
}
/**
* 以字节流的形式写入请求参数
* @param out
* @param obj
* @throws IOException
*/
public static void writeParam(OutputStream out, Object obj)
throws IOException {
out.write(obj.toString().getBytes("UTF-8"));
out.flush();
if(out != null){
out.close();
}
}
/**
* 以字符流的形式写入请求参数
* @param out
* @param obj
*/
@Deprecated
public static void printParam(PrintWriter out, Object obj){
out.print(obj.toString());
out.flush();
out.close();
}
/**
* 读取响应结果
* @param reader
* @return JSONObject
* @throws IOException
*/
public static JSONObject readResult(BufferedReader reader)
throws IOException {
String line = "";
StringBuilder sb = new StringBuilder();
while((line = reader.readLine()) != null){
sb.append(line);
}
reader.close();
return JSONObject.parseObject(sb.toString());
}
}
复制代码