HttpClient Get 과 Post 다른 인터페이스의 데 이 터 를 가 져 옵 니 다.

2654 단어 Web
인자 없 는 가 져 오기

	@Test

	public void doGet() throws Exception {
		//   httpclient  
		CloseableHttpClient client = HttpClients.createDefault();
		//   get  
		HttpGet get = new HttpGet("http://www.baidu.com");
		//    
		// HttpGet get = new HttpGet("http://www.baidu.com?id=1¶m=11");
		//     
		CloseableHttpResponse response = client.execute(get);
		//      
		HttpEntity entity = response.getEntity();
		String string = EntityUtils.toString(entity, "utf-8");
		System.out.println(string);
		//   
		response.close();
		client.close();
	}
	

get 매개 변수 가 져 오기
/**
	 *       
	 * @throws Exception
	 */
	@Test
	public void doGetWithParam() throws Exception {
		CloseableHttpClient client = HttpClients.createDefault();
		URIBuilder uri = new URIBuilder("http://www.baidu.com/s");
		uri.addParameter("wd", "  7");
		HttpGet get = new HttpGet(uri.build());
		CloseableHttpResponse response = client.execute(get);
		HttpEntity entity = response.getEntity();
		System.out.println(EntityUtils.toString(entity, "utf-8"));
		response.close();
		client.close();
	}

post 요청
@Test
	public void doPostWith() throws Exception {
		CloseableHttpClient client = HttpClients.createDefault();
		HttpPost post = new HttpPost("http://localhost:8082/httpclient/post.html");
//		URIBuilder uri = new URIBuilder("http://www.baidu.com/s");
//		uri.addParameter("wd", "  7");
//		HttpGet get = new HttpGet(uri.build());
		CloseableHttpResponse response = client.execute(post);
		HttpEntity entity = response.getEntity();
		System.out.println(EntityUtils.toString(entity, "utf-8"));
		response.close();
		client.close();
	}

post 매개 변수 요청 포함
@Test
	public void doPostWithParam() throws Exception {
		CloseableHttpClient client = HttpClients.createDefault();
		HttpPost post = new HttpPost("http://localhost:8082/httpclient/post1.html");
//		URIBuilder uri = new URIBuilder("http://www.baidu.com/s");
//		uri.addParameter("wd", "  7");
//		HttpGet get = new HttpGet(uri.build());
		List list = new ArrayList<>();
		list.add(new BasicNameValuePair("name", "  "));
		list.add(new BasicNameValuePair("pwd", "123"));
		StringEntity entity = new UrlEncodedFormEntity(list);
		post.setEntity(entity);
		CloseableHttpResponse response = client.execute(post);
		System.out.println(EntityUtils.toString(response.getEntity(), "utf-8"));
		response.close();
		client.close();
	}

좋은 웹페이지 즐겨찾기