网页提交表单数据,涉及到一系列请求参数。GET请求的参数,是通过URL传递的,通常以“?key1=value1&key2=value2”的形式进行传递。 POST请求的参数,通常是放在POST请求的消息体中,格式一般为JSON。例如,在某快递网站中输入快递单号查询快递信息,通过网络抓包获取的请求信息如下图所示,请求的方法为POST,提交的参数有2个。
请求地址:https://www.kuaidi100.com/autonumber/autoComNum。
快递单号:73123917441103。
抓包获得的参数:resultv2:1 text:73123917441103。
程序3-17是HttpClient工具提供的提交请求参数的方法。
//程序3-17
public class HttpClientPost {
public static void main(String[] args) throws Exception {
//初始化httpClient
HttpClient httpClient = HttpClients.custom().build();
//请求地址:https://www.kuaidi100.com/autonumber/autoComNum
String requestURL = "https://www.kuaidi100.com/autonumber/autoComNum";
//采用post方法
HttpPost httPost = new HttpPost(requestURL);
//建立一个NameValuePair数组,用于存储欲传送的参数
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("resultv2", "1"));
params.add(new BasicNameValuePair("text", "73123917441103"));
HttpResponse response = null;
try {
//表单参数提交
httPost.setEntity(new UrlEncodedFormEntity(params, HTTP.DEF_CONTENT_CHARSET));
response = httpClient.execute(httPost);
} catch (Exception e) {
e.printStackTrace();
} finally {
//释放连接
httPost.abort();
}
System.out.println(response.getStatusLine());
String entityString = EntityUtils.toString (response.getEntity(),"utf-8");
System.out.println(entityString);
}
}