java实现post类型接口的调用

(一)相关jar包坐标

		
		
			org.apache.httpcomponents
			httpclient
			4.5.2
		

(二)编写代码

/**
 * json格式提交参数
 * @param uri 接口地址
 * @param params 
 */
	public static void doJsonPost(String uri, String params) {
		// 创建一个post请求
		HttpPost post = new HttpPost(uri);
		post.setHeader("X-Lemonban-Media-Type", "lemonban.v1");
		post.setHeader("Content-Type", "application/json");
		try {
			// 设置参数
			post.setEntity(new StringEntity(params, "utf-8"));
			// 创建客户端
			HttpClient httpClient = HttpClients.createDefault();
			// 发送请求
			HttpResponse response = httpClient.execute(post);
			getCodeAndResult(response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 表单方式提交uri
	 * @param uri uri地址
	 * @param params  请求参数
	 */
	public static void doFormPost(String uri, String params) {
		// 创建一个post请求
		HttpPost post = new HttpPost(uri);
		post.setHeader("X-Lemonban-Media-Type", "lemonban.v1");
		post.setHeader("Content-Type", "application/x-www-form-urlencoded");
		try {
			// 设置参数
			post.setEntity(new StringEntity(params, "utf-8"));
			// 创建客户端
			HttpClient httpClient = HttpClients.createDefault();
			// 发送请求
			HttpResponse response = httpClient.execute(post);
			getCodeAndResult(response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

		/**
	 * 根据响应结果获取状态码和body
	 * 
	 * @param response 响应结果
	 * @throws IOException
	 */
	private static void getCodeAndResult(HttpResponse response) throws IOException {
		// 获取状态码
		int code = response.getStatusLine().getStatusCode();
		System.out.println(code);
		// 获取body
		String result = EntityUtils.toString(response.getEntity());
		System.out.println(result);
	}

你可能感兴趣的:(接口自动化测试)