工欲善其事,必先利其器-java高级测试进阶之接口自动化测试工具类(一)处理http请求。

解决http接口测试中常见的问题,涵盖json,XML两种数据格式,get,post,raw(请求为字符串形式)请求方式。
package com.utils.api;

import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

public class DoRequestUtils {
	
	public static void main(String[] args) throws Exception {
	    String url="访问地址";
		DoRequestUtils doRequestUtils=new DoRequestUtils();
		
		Map<String,String> map=new HashMap<>();
		map.put("userName", "用户名");
		map.put("passWord", "密码");
		doRequestUtils.dopost(url, map, "utf-8");
		
	}
	

	CloseableHttpClient httpclient = HttpClients.custom()
	
			.setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build())
			.build();

	public String dopost(String url, Map<String, String> map, String charset) throws Exception {

		HttpPost httpPost = new HttpPost(url);

		List<NameValuePair> ParamList = new ArrayList<NameValuePair>();
		// List<NameValuePair> ParamList = new Vector<NameValuePair>();

		Iterator<Entry<String, String>> iterator = map.entrySet().iterator();// entrySet

		while (iterator.hasNext()) {
			Entry<String, String> elem = iterator.next();
			ParamList.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));			
																																						
		}

		if (ParamList.size() > 0) {
			httpPost.setEntity(new UrlEncodedFormEntity(ParamList, charset));

			System.out.println(url + "?" + URLEncodedUtils.format(ParamList, charset));
		}

		CloseableHttpResponse response = httpclient.execute(httpPost);

		HttpEntity resultEntity = response.getEntity();

		String originresult = EntityUtils.toString(resultEntity, charset);
		String ContentType = (response.getEntity()).toString();

		if (ContentType.contains("application/json")) {

			if (originresult.contains("null")) {

				System.out.println("JsonFormater:"+JsonFormater(originresult));

			} else {

				System.out.println(FastJsonFormater(originresult));

			}
		} else {

			System.out.println("originresult:"+originresult);

		}

		System.out.println(originresult.length()+ "b"+"----"+originresult.length()/1024 + "kb");

		return originresult;

	}

	public String doget(String url, LinkedList<BasicNameValuePair> params, String charset) throws Exception {

		System.out.println(params);

		HttpGet httpGet = new HttpGet(url + "" + URLEncodedUtils.format(params, charset));
		System.out.println(httpGet);


		httpGet.setHeader("Referer", "http://www.the-x.cn/");
		httpGet.setHeader("User-Agent", "Firefox/3.6.6 Greatwqs");
		httpGet.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		httpGet.setHeader("Accept-Language", "zh-cn,zh;q=0.5");
		httpGet.setHeader("Host", "www.the-x.cn");
		httpGet.setHeader("Accept", "application/json, text/javascript, */*; q=0.01");
		httpGet.setHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
		httpGet.setHeader("X-Requested-With", "XMLHttpRequest");

		//模拟请求头,请求一般不限制。
		// httpGet.setHeader("Accept","application/json");
		// httpGet.setHeader("Content-type","application/json");
		CloseableHttpResponse response = httpclient.execute(httpGet);

		System.out.println(response);

		Header headers[] = response.getAllHeaders();

		int i = 0;
		while (i < headers.length) {
			System.out.println(headers[i].getName() + ":  " + headers[i].getValue());
			i++;
		}

		HttpEntity resultEntity = response.getEntity();
		System.out.println(resultEntity.getContentType());
		String result = EntityUtils.toString(resultEntity, charset);
		System.out.println(result);
		//
		// if (response.) {
		//
		// }

		return result;

	}

	
	//raw常见两种请求参数形式json,xml处理。
	public String dopostrawjson(String url, String body, String charset) throws Exception {

		System.out.println(body);

		HttpPost httpPost = new HttpPost(url);

		httpPost.setEntity(new StringEntity(body, charset));

		CloseableHttpResponse response = httpclient.execute(httpPost);

		HttpEntity resultEntity = response.getEntity();

		String result = JsonFormater(EntityUtils.toString(resultEntity, charset));

		String string = (response.getEntity()).toString();// 

		System.out.println(result);

		if (string.contains("application/json")) {

			System.out.println(result);
		}

		return result;

	}

	public String dopostrawxml(String url, String body) throws Exception {

		HttpPost httpHost = new HttpPost(url);

		httpHost.setEntity(new StringEntity(body, "UTF-8"));

		CloseableHttpResponse response = httpclient.execute(httpHost);

		HttpEntity httpEntity = response.getEntity();

		String entitystring = EntityUtils.toString(httpEntity, "UTF-8");

		String result = xmlFormater(entitystring);

		System.out.println(result);

		return result;

	}

	//接口返回参数格式化,json,xml。
	public static String JsonFormater(String JsonString) {//

		JsonParser jp = new JsonParser();// 

		JsonElement je = jp.parse(JsonString);// 

		if (JsonString.contains("null")) {//处理返回参数为null情况

			Gson gsonbuilder = new GsonBuilder().serializeNulls().setPrettyPrinting().create();

			String prettyJsonString = gsonbuilder.toJson(je);
			return prettyJsonString;

		} else {
			Gson gsonbuilder = new GsonBuilder().setPrettyPrinting().create();

			String prettyJsonString = gsonbuilder.toJson(je);

			return prettyJsonString;

		}

		// Gson gson = new GsonBuilder().setPrettyPrinting().create();

	}

	public static String FastJsonFormater(String result) {// fastjson,对比gson,另一种方法。

		JSONObject jSONObject = JSON.parseObject(result);

		String prettyJsonString = JSON.toJSONString(jSONObject, SerializerFeature.WriteMapNullValue);
		
		String prettyJsonString1 = JSON.toJSONString(jSONObject, SerializerFeature.PrettyFormat);//不处理返回参数为null,对象会不显示。

		return prettyJsonString;
	}

	public static String xmlFormater(String str) throws Exception {

		SAXReader reader = new SAXReader();

		StringReader in = new StringReader(str);

		Document doc = reader.read(in);// 

		OutputFormat formter = OutputFormat.createPrettyPrint();
		// formter.setEncoding("utf-8");

		StringWriter out = new StringWriter();
		XMLWriter writer = new XMLWriter(out, formter);
		// System.out.println(writer);
		writer.write(doc);
		writer.close();
		return out.toString();

	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值