Java+ httpClient 测试接口

Post接口

public void login() throws Exception {
     
	//创建httpclient链接
	CloseableHttpClient client=HttpClients.createDefault();
	//创建Post请求
	HttpPost post=new HttpPost("http://index.php?s=/index/user/login.html");
	//添加http请求头
	post.setHeader("X-Requested-With", "XMLHttpRequest");
	//添加Post请求参数
	BasicNameValuePair userNameValuePair=new BasicNameValuePair("accounts", "m");
	BasicNameValuePair pwdValuePair=new BasicNameValuePair("pwd", "m=");
	ArrayList<NameValuePair>  paramsList=new ArrayList<NameValuePair>();
	paramsList.add(userNameValuePair);
	paramsList.add(pwdValuePair);
	//将参数转换为entity
	UrlEncodedFormEntity postEntity=new UrlEncodedFormEntity(paramsList);
	//设置post的entity对象
	post.setEntity(postEntity);
	//获取响应数据
	CloseableHttpResponse response=client.execute(post);
	//将响应结果装换为entity;
	String restring=EntityUtils.toString(response.getEntity());
	System.out.println(restring);

Post Json/xml接口

	public void jsonTest() throws Exception {
     
		// 创建httpclient链接
		CloseableHttpClient client = HttpClients.createDefault();
		// 创建Post请求
		HttpPost postJson = new HttpPost("http://localhost:8080");
		postJson.setHeader("Content-Type", "Application/json");
		String paramString="{\"userName\":\"test\"}";
		// 将参数转换为entity
		HttpEntity postEntity = new StringEntity(paramString);
		postJson.setEntity(postEntity);
		// 获取响应数据
		CloseableHttpResponse response = client.execute(postJson);
		// 将响应结果装换为entity;
		String restring = EntityUtils.toString(response.getEntity());
		System.out.println(restring);

	}

Get接口

	public void getStu() throws Exception {
     
		// 创建httpclient链接
		CloseableHttpClient client = HttpClients.createDefault();
		// 创建Get请求
		HttpGet get = new HttpGet("http://localhost:8080/?id=1");
		// 获取响应数据
		CloseableHttpResponse response = client.execute(get);
		// 将响应结果装换为entity;
		String restring = EntityUtils.toString(response.getEntity());
		System.out.println(restring);

	}

上传文件接口

	public void upLoadFile() throws Exception {
     
		// 创建httpclient链接
		CloseableHttpClient client = HttpClients.createDefault();
		// 创建Get请求
		HttpPost upLoadFile= new HttpPost("http://localhost:8080");
		//添加文件
		FileBody fileBody=new FileBody(new File("C:\\Users\\Desktop\\a.txt"));
		//创建文件体
		MultipartEntityBuilder builder=MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
		HttpEntity httpEntity=builder.addPart("file", fileBody).build();
		upLoadFile.setEntity(httpEntity);
		// 获取响应数据
		CloseableHttpResponse response = client.execute(upLoadFile);
		// 将响应结果装换为entity;
		String restring = EntityUtils.toString(response.getEntity());
		System.out.println(restring);

	}

你可能感兴趣的:(Java学习,软件测试,接口测试,java)