A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

【郑州校区】使用HttpClient进行POST请求

3.4.1知识概述
[AppleScript] 纯文本查看 复制代码
package cn.itcast.spider.httpClient;

import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.nio.charset.Charset;
import java.util.ArrayList;

/**
 使用 httpclient 来进行post请求
 */
public class HCPost {
   public static void main(String[] args) throws Exception {
      // 1.拿到一个httpclient的对象
      CloseableHttpClient httpClient = HttpClients.createDefault();
      // 2.设置请求方式和请求信息
//    HttpGet httpGet = new HttpGet("http://www.itcast.cn");
      HttpPost httpPost = new HttpPost("http://www.itcast.cn");
      
      //2.1 提交header头信息
      httpPost.addHeader("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36");
      //2.1 提交请求体
      //提交方式1:一般用在原生ajax请求
//    httpPost.setEntity(new StringEntity("username=zhangsan&passwd=123"));
      //提交方式2:大多数的情况下用这种方式
      ArrayList<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
      parameters.add(new BasicNameValuePair("username", "zhangsan"));
      parameters.add(new BasicNameValuePair("passwd", "123"));
      httpPost.setEntity(new UrlEncodedFormEntity(parameters));
      
      // 3.执行请求
      CloseableHttpResponse response = httpClient.execute(httpPost);
      // 4.获取返回值
      String html = EntityUtils.toString(response.getEntity(),Charset.forName("utf-8"));
      // 5.打印
      System.out.println(html);

   }
}
3.4.2视频详情
3.4.3总结与补充
        无
3.4.4课堂提问与练习
        无
3.4.5习题答案
        无
传智播客·黑马程序员郑州校区地址
河南省郑州市 高新区长椿路11号大学科技园(西区)东门8号楼三层
联系电话 0371-56061160/61/62
来校路线  地铁一号线梧桐街站A口出

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马