具体代码:
package cn.itcast.crawler.test;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
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.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
public class HttpPostParamTest {
public static void main(String[] args) throws Exception {
//1.创建HttpClient对象
CloseableHttpClient httpClient= HttpClients.createDefault();
//2.创建HttpPost对象,设置URL地址
HttpPost httpPost=new HttpPost("http://yun.itheima.com/search");;
//声明list集合,用来分装表单中的参数
//要求:设置请求的地址是:http://yun.itheima.com/search?keys=java
List<NameValuePair> params=new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("keys","java"));
// 创建表单的Entity对象,第一个参数是封装好的表单数据,第二个参数就是编码方式
UrlEncodedFormEntity formEntity=new UrlEncodedFormEntity(params,"utf8");
//设置表单的Entity对象到Post请求中
httpPost.setEntity(formEntity);
//使用httpClient发起响应获取repsonse
CloseableHttpResponse response=null;
try {
response=httpClient.execute(httpPost);
//4.解析响应,获取数据
//判断状态码是否是200
if(response.getStatusLine().getStatusCode()==200){
HttpEntity httpEntity=response.getEntity();
String content=EntityUtils.toString(httpEntity,"utf8");
System.out.println(content.length());
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
执行结果:
在带参数的post请求中,参数并不会出现在地址栏中,
与不带参数的post请求相比较,带参数的post代码的核心内容就是上面代码中添加了背景颜色的代码