使用httpClient模拟浏览器发送请求

  1. 使用httpClient发送无参数get请求,代码如下
		//创建一个httpClient对象
		CloseableHttpClient httpClient=HttpClients.createDefault();
		//创建一个Get对象
		HttpGet get=new HttpGet("http://www.sogou.com");
		//执行请求
		CloseableHttpResponse response = httpClient.execute(get);
		//取响应的结果
		int statusCode = response.getStatusLine().getStatusCode();
		System.out.println(statusCode);
		HttpEntity entity = response.getEntity();
		String string = EntityUtils.toString(entity,"utf-8");
		System.out.println(string);
		//关闭httpClient
		response.close();
		httpClient.close();
  1. 使用httpClient发送带参数的get请求,有两种方式
    第一种,在上述无参数的方法中,在创建get对象时,将参数附在url后面,例如:HttpGet get=new HttpGet(“http://www.sogou.com?query=“花千骨””);
    第二种方法,创建一个URL对象,将参数添加进URL对象中,再使用URL对象创建get对象,代码如下:
		//创建一个httpclient对象
		CloseableHttpClient httpClient=HttpClients.createDefault();
		//创建一个url对象并添加参数
		URIBuilder uriBuilder=new URIBuilder("https://www.sogou.com/sie");
		uriBuilder.addParameter("query", "花千骨");
		HttpGet get=new HttpGet(uriBuilder.build());
		//执行请求,获得响应
		CloseableHttpResponse response = httpClient.execute(get);
		//取响应的结果
		int statusCode = response.getStatusLine().getStatusCode();
		System.out.println(statusCode);
		HttpEntity entity = response.getEntity();
		String string = EntityUtils.toString(entity,"utf-8");
		System.out.println(string);
		//关闭httpclient
		response.close();
		httpClient.close();
  1. 使用httpClient发送无参数的post请求,与无参数的get请求类似,区别只是不创建get对象,而是创建post对象,代码如下:
CloseableHttpClient httpClient=HttpClients.createDefault();
		//创建一个post对象
		HttpPost post=new HttpPost("http://localhost:8082/httpclient/post.html");
		CloseableHttpResponse response = httpClient.execute(post);
		String string = EntityUtils.toString(response.getEntity());
		System.out.println(string);
		response.close();
		httpClient.close();
  1. 使用httpClient发送有参数的post请求,比较复杂,需创建Entity对象,先模拟表单,创建一个基类是实现NameValuePair接口的list,然后将参数使用BasicNameValuePair类添加进list当中,在将此list封装成Entity对象,然后设置给post,代码如下:
CloseableHttpClient httpClient=HttpClients.createDefault();
		//创建一个post对象
		HttpPost post=new HttpPost("http://localhost:8082/httpclient/post.html");
		//创建一个Entity,模拟一个表单
		List kvList=new ArrayList<>();
		kvList.add(new BasicNameValuePair("name", "zhangsan"));
		kvList.add(new BasicNameValuePair("password","123456"));
		//包装成一个Entity对象
		StringEntity entity=new UrlEncodedFormEntity(kvList);
		//设置请求的内容
		post.setEntity(entity);
		CloseableHttpResponse response = httpClient.execute(post);
		String string = EntityUtils.toString(response.getEntity());
		System.out.println(string);
		response.close();
		httpClient.close();

你可能感兴趣的:(初学者,烂笔头)