本文共 3477 字,大约阅读时间需要 11 分钟。
引入maven依赖
<!-- HttpClient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.3</version> </dependency> <!-- 日志 --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.25</version> </dependency>
加入日志配置文件
log4j.rootLogger=DEBUG,A1log4j.logger.cn.itcast = DEBUGlog4j.appender.A1=org.apache.log4j.ConsoleAppenderlog4j.appender.A1.layout=org.apache.log4j.PatternLayoutlog4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c]-[%p] %m%n
代码如下:
public static void getTest()throws Exception{ CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet("http://www.itcast.cn?pava=zhangxm"); CloseableHttpResponse response = httpClient.execute(httpGet); if (response.getStatusLine().getStatusCode() == 200) { String content = EntityUtils.toString(response.getEntity(), "UTF-8"); System.out.println(content); }}
/** * java 代码发送post请求并传递参数 * @throws Exception */ public static void postTest () throws Exception{ //创建HttpClient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(1000)//设置创建连接的最长时间 .setConnectionRequestTimeout(500)//设置获取连接的最长时间 .setSocketTimeout(10 * 1000)//设置数据传输的最长时间 .build(); //创建HttpGet请求 HttpPost httpPost = new HttpPost("http://www.itcast.cn/"); httpPost.setConfig(requestConfig); CloseableHttpResponse response = null; try { //声明存放参数的List集合 List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("pava", "zhangxm")); //创建表单数据Entity UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "UTF-8"); //设置表单Entity到httpPost请求对象中 httpPost.setEntity(formEntity); //使用HttpClient发起请求 response = httpClient.execute(httpPost); //判断响应状态码是否为200 if (response.getStatusLine().getStatusCode() == 200) { //如果为200表示请求成功,获取返回数据 String content = EntityUtils.toString(response.getEntity(), "UTF-8"); //打印数据长度 System.out.println(content); } } catch (Exception e) { e.printStackTrace(); } finally { //释放连接 if (response == null) { try { response.close(); } catch (IOException e) { e.printStackTrace(); } httpClient.close(); } } }
如果每次请求都要创建HttpClient,会有频繁创建和销毁的问题,可以使用连接池来解决这个问题。
/**
转载地址:http://sxfwz.baihongyu.com/