java.net 发送http请求
代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; /** * Created by deng on 2020/3/24. * 发送HTTP请求 */ public class HttpClient { public static void main(String[] args) { String url = "https://www.baidu.com"; String s = HttpClient.sendHttpRequest(url, RequestMethod.GET); System.out.println(s); } /** * @param urlParam url * @param requestMethod 请求方式 * @return 返回String类型的字符串 ,如果请求失败,返回null */ public static String sendHttpRequest(String urlParam,RequestMethod requestMethod){ HttpURLConnection con = null; BufferedReader buffer = null; StringBuffer resultBuffer = null; InputStream ins = null; try { URL url = new URL(urlParam); //得到连接对象 con = (HttpURLConnection) url.openConnection(); //设置请求类型 switch (requestMethod){ case GET: con.setRequestMethod("GET"); break; case POST: con.setRequestMethod("POST"); break; } //据说post请求必须设置这两条,暂时不知道 con.setDoOutput(true); //允许写出 con.setDoInput(true); //允许读入 con.setUseCaches(false); //不使用缓存 //得到响应码 int responseCode = con.getResponseCode(); if(responseCode == HttpURLConnection.HTTP_OK){ //请求成功,得到响应流 ins = con.getInputStream(); //转化为字符串 resultBuffer = new StringBuffer(); String line; //注意响应体的编码格式,可能会有乱码 buffer = new BufferedReader(new InputStreamReader(ins,"GBK")); while((line=buffer.readLine())!=null){ resultBuffer.append(line); } //将resultBuffer返回即可 return resultBuffer.toString(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { if(ins!=null){ try { ins.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; } } enum RequestMethod{ GET, //get请求 POST //post请求 }