httpclient post 發送Json數據

        String url = "http://127.0.0.1:8099/login";
	String json = "{\"login_name\": \"18800000000\",\"login_password\": \"123456\"}";
	@Test
	public void post() throws ClientProtocolException, IOException{
		//建立client
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			//建立post請求
			HttpPost httppost = new HttpPost(url);
			//json
			StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
			httppost.setEntity(entity);
			System.out.println("executing request " + httppost.getRequestLine());
			//執行post請求
			CloseableHttpResponse response = httpclient.execute(httppost);
			try {
				System.out.println("----------------------------------------");
				//狀態
				System.out.println(response.getStatusLine());
				//響應實體
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					System.out.println(EntityUtils.toString(resEntity));
				}
				//關閉HttpEntity流
				EntityUtils.consume(resEntity);
			} finally {
				response.close();
			}
		} finally {
			httpclient.close();
		}
	}
相關文章
相關標籤/搜索