작업 을 잘 하려 면 먼저 그 기 - 자바 고급 테스트 진급 의 인터페이스 자동화 테스트 도구 류 (1) 에서 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 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 map, String charset) throws Exception {

		HttpPost httpPost = new HttpPost(url);

		List ParamList = new ArrayList();
		// List ParamList = new Vector();

		Iterator> iterator = map.entrySet().iterator();// entrySet

		while (iterator.hasNext()) {
			Entry 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 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();

	}

}

좋은 웹페이지 즐겨찾기