1. 程式人生 > >HttpClient方式呼叫介面的例項

HttpClient方式呼叫介面的例項

使用HttpClient的方式呼叫介面的例項。

	/**
	 * 測試呼叫第三方介面
	 */
	@RequestMapping(value = "/test", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Response test(@RequestBody QueryMonthRentOrder query) {
		Response response = new Response<>(ResponseCodeType.SUCCESS);
		// 把物件轉換成json字串
		Gson gson = new Gson();
		String json = gson.toJson(query);
		// 請求介面地址
		String url = "https://blog.csdn.net/qq_36725282";

		HttpClient httpclient = null;
		PostMethod post = null;
		GetMethod get = null;
		try {
			// 建立連線
			httpclient = new HttpClient();
			post = new PostMethod(url);
			// 設定編碼方式
			post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
			// 新增引數
			post.setRequestBody(json);
			// 設定表頭
			post.setRequestHeader("XXXXXX", "XXXXXX");
			post.setRequestHeader("Content-Type", "application/json");
			// 執行請求
			httpclient.executeMethod(post);
			// 介面返回資訊
			String info = new String(post.getResponseBody(), "UTF-8");
			System.out.println("***************" + info);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 關閉連線,釋放資源
			post.releaseConnection();
			((SimpleHttpConnectionManager) httpclient.getHttpConnectionManager()).shutdown();
		}

		response.setData("");
		return response;
	}