使用HttpClient進行POST請求
阿新 • • 發佈:2019-05-16
請求方式 encode basic oid 使用 kit void tca rgs
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);
}
}
使用HttpClient進行POST請求