Java实现HTTP请求
import org.apache.commons.lang3.StringUtils;
import java.io.*;
import java.net.*;
public class HTTPUtil {
public static String HTTPGet(String url, String param) {
InputStream inputStream = null;
BufferedReader bufferedReader = null;
HttpURLConnection connection = null;
StringBuffer stringBuffer = null;
try {
String urlNameString = url + (StringUtils.isBlank(param) ? "" : ("?" + param));
//创建连接
URL realUrl = new URL(urlNameString);
// URL url = new URL("http://192.168.31.179:19303/entity-area/queryAreaList");
//通过远程url连接对象打开一个连接,强转成httpURLConnection类
connection = (HttpURLConnection) realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "**");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// URL连接可以用于输入和/或输出。如果想使用URL连接作为输入,设置DoInput *标志为true,如果不是假的。默认为true
connection.setDoOutput(true);
connection.setDoInput(true);
// 获取URLConnection对象对应的输出流
PrintWriter out = new PrintWriter(connection.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
//发送请求
connection.connect();
inputStream = connection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
bufferedReader = new BufferedReader(inputStreamReader);
stringBuffer = new StringBuffer();
String temp = null;
while ((temp = bufferedReader.readLine()) != null) {
stringBuffer.append(temp);
stringBuffer.append("rn");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != inputStream) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != inputStreamReader) {
try {
inputStreamReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != bufferedReader) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != connection) {
//关闭远程连接
connection.disconnect();
}
}
return stringBuffer.toString();
}
}



