简介:使用URLConnection实现了调用http请求,该方法不支持调用https请求。https调用方式可查看:HttpURLConnection实现和HttpClient实现
1.使用GET方式调用http请求代码:
public static String requestHttpGet(String url,String params){String result = "";try {if (StringUtil.isNotEmpty(params)){//如果有参数,将参数写入url += "?"+params;}URL requestUrl = new URL(url);URLConnection connection = requestUrl.openConnection();//设置是否使用缓存connection.setUseCaches(false);connection.setConnectTimeout(100000);connection.setReadTimeout(100000);InputStream in = connection.getInputStream();BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"));String line = null;while ((line=reader.readLine())!=null){result += line;}}catch (Exception e){e.printStackTrace();}return result;}
2.使用POST方式调用http请求代码:
public static String requestHttpPost(String url,String params){String result = "";try {URL requestUrl = new URL(url);URLConnection connection = requestUrl.openConnection();//设置是否使用缓存connection.setUseCaches(false);connection.setConnectTimeout(100000);connection.setReadTimeout(100000);if (StringUtil.isNotEmpty(params)){//如果有参数,将参数写入connection.setDoOutput(true);connection.getOutputStream().write(params.getBytes("utf-8"));}InputStream in = connection.getInputStream();BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"));String line = null;while ((line=reader.readLine())!=null){result += line;}}catch (Exception e){e.printStackTrace();}return result;}
3.测试代码:
public static void main(String[] args) {String url = "http://www.baidu.com";System.out.println(requestHttpGet(url,null));System.out.println(requestHttpPost(url,null));}