import java.io.*;importjava.net.HttpURLConnection;importjava.net.URL;importjava.net.URLDecoder;importjava.net.URLEncoder;importjava.util.HashMap;importjava.util.Map;public classHttpUtil {public static void main(String[] args) throwsIOException {
Map map = new HashMap<>();
map.put("Accept", "*/*");
map.put("Pragma", "no-cache");
map.put("Connection", "keep-alive");
map.put("Cache-Control", "no-cache");
map.put("Accept-Language", "zh-CN,zh;q=0.9");//map.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36");
String url= "http://www.baidu.com/";
String html=get(url, map);
System.out.println(html);
}/*** Send a get request
*
*@paramurl
*@returnresponse
*@throwsIOException*/
public static String get(String url) throwsIOException {return get(url, null);
}/*** Send a get request
*
*@paramurl Url as string
*@paramheaders Optional map with headers
*@returnresponse Response as string
*@throwsIOException*/
public static String get(String url, Map headers) throwsIOException {return fetch("GET", url, null, headers);
}/*** Send a post request
*
*@paramurl Url as string
*@parambody Request body as string
*@paramheaders Optional map with headers
*@returnresponse Response as string
*@throwsIOException*/
public static String post(String url, String body, Map headers) throwsIOException {return fetch("POST", url, body, headers);
}/*** Send a post request
*
*@paramurl Url as string
*@parambody Request body as string
*@returnresponse Response as string
*@throwsIOException*/
public static String post(String url, String body) throwsIOException {return post(url, body, null);
}/*** Post a form with parameters
*
*@paramurl Url as string
*@paramparams map with parameters/values
*@returnresponse Response as string
*@throwsIOException*/
public static String postForm(String url, Map params) throwsIOException {return postForm(url, params, null);
}/*** Post a form with parameters
*
*@paramurl Url as string
*@paramparams Map with parameters/values
*@paramheaders Optional map with headers
*@returnresponse Response as string
*@throwsIOException*/
public static String postForm(String url, Map params, Map headers) throwsIOException {//set content type
if (headers == null) {
headers= new HashMap<>();
}
headers.put("Content-Type", "application/x-www-form-urlencoded");//parse parameters
String body = "";if (params != null) {boolean first = true;for(String param : params.keySet()) {if(first) {
first= false;
}else{
body+= "&";
}
String value=params.get(param);
body+= URLEncoder.encode(param, "UTF-8") + "=";
body+= URLEncoder.encode(value, "UTF-8");
}
}returnpost(url, body, headers);
}/*** Send a put request
*
*@paramurl Url as string
*@parambody Request body as string
*@paramheaders Optional map with headers
*@returnresponse Response as string
*@throwsIOException*/
public static String put(String url, String body, Map headers) throwsIOException {return fetch("PUT", url, body, headers);
}/*** Send a put request
*
*@paramurl Url as string
*@returnresponse Response as string
*@throwsIOException*/
public static String put(String url, String body) throwsIOException {return put(url, body, null);
}/*** Send a delete request
*
*@paramurl Url as string
*@paramheaders Optional map with headers
*@returnresponse Response as string
*@throwsIOException*/
public static String delete(String url, Map headers) throwsIOException {return fetch("DELETE", url, null, headers);
}/*** Send a delete request
*
*@paramurl Url as string
*@returnresponse Response as string
*@throwsIOException*/
public static String delete(String url) throwsIOException {return delete(url, null);
}/*** Append query parameters to given url
*
*@paramurl Url as string
*@paramparams Map with query parameters
*@returnurl Url with query parameters appended
*@throwsIOException*/
public static String appendQueryParams(String url, Map params) throwsIOException {
String fullUrl=url;if (params != null) {boolean first = (fullUrl.indexOf('?') == -1);for(String param : params.keySet()) {if(first) {
fullUrl+= '?';
first= false;
}else{
fullUrl+= '&';
}
String value=params.get(param);
fullUrl+= URLEncoder.encode(param, "UTF-8") + '=' + URLEncoder.encode(value, "UTF-8");
}
}returnfullUrl;
}/*** Retrieve the query parameters from given url
*
*@paramurl Url containing query parameters
*@returnparams Map with query parameters
*@throwsIOException*/
public static Map getQueryParams(String url) throwsIOException {
Map params = new HashMap<>();int start = url.indexOf('?');while (start != -1) {//read parameter name
int equals = url.indexOf('=', start);
String param= "";if (equals != -1) {
param= url.substring(start + 1, equals);
}else{
param= url.substring(start + 1);
}//read parameter value
String value = "";if (equals != -1) {
start= url.indexOf('&', equals);if (start != -1) {
value= url.substring(equals + 1, start);
}else{
value= url.substring(equals + 1);
}
}
params.put(URLDecoder.decode(param,"UTF-8"), URLDecoder.decode(value, "UTF-8"));
}returnparams;
}/*** Returns the url without query parameters
*
*@paramurl Url containing query parameters
*@returnurl Url without query parameters
*@throwsIOException*/
public static String removeQueryParams(String url) throwsIOException {int q = url.indexOf('?');if (q != -1) {return url.substring(0, q);
}else{returnurl;
}
}/*** Send a request
*
*@parammethod HTTP method, for example "GET" or "POST"
*@paramurl Url as string
*@parambody Request body as string
*@paramheaders Optional map with headers
*@returnresponse Response as string
*@throwsIOException*/
public static String fetch(String method, String url, String body, Map headers) throwsIOException {//connection
URL u = newURL(url);
HttpURLConnection conn=(HttpURLConnection) u.openConnection();
conn.setConnectTimeout(100000);
conn.setReadTimeout(300000);//method
if (method != null) {
conn.setRequestMethod(method);
}//headers
if (headers != null) {for(String key : headers.keySet()) {
conn.addRequestProperty(key, headers.get(key));
}
}//body
if (body != null) {
conn.setDoOutput(true);
OutputStream os=conn.getOutputStream();
os.write(body.getBytes());
os.flush();
os.close();
}//response
InputStream is =conn.getInputStream();
String response=streamToString(is);
is.close();//handle redirects
if (conn.getResponseCode() == 301) {
String location= conn.getHeaderField("Location");returnfetch(method, location, body, headers);
}returnresponse;
}/*** Read an input stream into a string
*
*@paramin
*@return*@throwsIOException*/
public static String streamToString(InputStream in) throwsIOException {
StringBuffer out= newStringBuffer();
BufferedReader br= new BufferedReader(new InputStreamReader(in, "UTF-8"));
String line;while ((line = br.readLine()) != null) {
out.append(line);
}//byte[] b = new byte[4096];//for (int n; (n = in.read(b)) != -1; ) {//out.append(new String(b, 0, n));//}
returnout.toString();
}
}