HTTPClient Get請求 POST請求

GET:java

@Test
	public void doGet() throws Exception {
		//建立一個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();
	}

ParamGet:web

@Test
	public void doGetWithParam() throws Exception{
		//建立一個httpclient對象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		//建立一個uri對象
		URIBuilder uriBuilder = new URIBuilder("http://www.sogou.com/web");
		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();
	}

 

 

 

POST:post

@Test
	public void doGetWithParam() throws Exception{
		//建立一個httpclient對象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		//建立一個uri對象
		URIBuilder uriBuilder = new URIBuilder("http://www.sogou.com/web");
		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();
	}

​ParamPost:ui

@Test
	public void doPostWithParam() throws Exception{
		CloseableHttpClient httpClient = HttpClients.createDefault();
	 
		//建立一個post對象  
		HttpPost post = new HttpPost("http://localhost:8082/httpclient/post.action");
		//建立一個Entity。模擬一個表單
		List<NameValuePair> kvList = new ArrayList<>();
		kvList.add(new BasicNameValuePair("username", "張三"));
		kvList.add(new BasicNameValuePair("password", 	"123"));
		
		//包裝成一個Entity對象 
		StringEntity entity = new UrlEncodedFormEntity(kvList, "utf-8");
		//設置請求的內容 
		post.setEntity(entity);
		
		//執行post請求
		CloseableHttpResponse response = httpClient.execute(post);
		String string = EntityUtils.toString(response.getEntity());
		System.out.println(string);
		response.close();
		httpClient.close();
	}
相關文章
相關標籤/搜索