使用HttpClient4实现API测试实战(1)
编程技术  /  houtizong 发布于 3年前   51
commons-beanutils-1.8.0.jarcommons-collections-3.2.1.jarcommons-lang-2.4.jarcommons-logging-1.0.4.jardom4j-1.6.1.jarezmorph-1.0.6.jarhttpclient-4.0.1.jarhttpcore-4.0.1.jar
public class HttpClientUtil {public static DefaultHttpClient httpClient = null;public static HttpClient getInstance() {if (httpClient == null) {httpClient = new DefaultHttpClient();}return httpClient;}public static void disconnect() {httpClient = null;}public static String doGet(String url) {return doGet(url, new ArrayList<BasicNameValuePair>());}public static String doGet(String url, List<BasicNameValuePair> data) {/* 建立HTTP Post连线 */HttpGet httpGet = new HttpGet(url);try {HttpResponse httpResponse = HttpClientUtil.getInstance().execute(httpGet);if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {return EntityUtils.toString(httpResponse.getEntity());} else {System.out.println("doGet Error Response: " + httpResponse.getStatusLine().toString());}} catch (Exception e) {e.printStackTrace();}return null;}public static String doPost(String url) {return doPost(url, new ArrayList<BasicNameValuePair>());}public static String doPost(String url, List<BasicNameValuePair> data) {/* 建立HTTP Post连线 */HttpPost httpPost = new HttpPost(url);try {// 发出HTTP request// httpPost.setEntity(new UrlEncodedFormEntity(data, HTTP.UTF_8));httpPost.setEntity(new UrlEncodedFormEntity(data, "UTF-8"));// 取得HTTP responseHttpResponse httpResponse = HttpClientUtil.getInstance().execute(httpPost);// 若状态码为200 okif (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 取出回应字串return EntityUtils.toString(httpResponse.getEntity());} else {System.out.println("doPost Error Response: " + httpResponse.getStatusLine().toString());}} catch (Exception e) {e.printStackTrace();}return null;}}
public class XmlUtil {/** * 将xml格式的字符串转化成可以解析的Document对象 * * @param xml * @return */public static Document parseXmlToDocument(String xml) {Document doc = null;if (xml != null && !xml.equals("")) {StringReader sr = new StringReader(xml);InputSource is = new InputSource(sr);DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();DocumentBuilder builder = null;try {builder = factory.newDocumentBuilder();doc = builder.parse(is);} catch (Exception e) {e.printStackTrace();}}return doc;}// 从xml文件中获取节点的值public static String getContentFromXml(String xml, String NodeName) {return getContentFromXml(xml, NodeName, 0);}public static String getContentFromXml(String xml, String NodeName, int index) {String value = "";try {Document doc = XmlUtil.parseXmlToDocument(xml);if (doc != null) {Node node = doc.getElementsByTagName(NodeName).item(index);if (node != null) {value = node.getFirstChild().getTextContent();}}} catch (Exception e) {return null;}return value;}}
public class ApiUtil {private static final String OAUTH_COMSUMER_KEY = "key";private static final String OAUTH_COMSUMER_SECRET = "password";private static final String API_URL = "http://localhost/api";private static String token = null;public static String getToken() {if (token == null) {token = accountToken(OAUTH_COMSUMER_KEY, OAUTH_COMSUMER_SECRET);}return token;}// Oauth的accountToken的获得public static String accountToken(String key, String secret) {List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>(0);params.add(new BasicNameValuePair("oauth_consumer_key", key));params.add(new BasicNameValuePair("oauth_consumer_secret", secret));String xml = HttpClientUtil.doPost(API_URL + "/accountToken", params);if (hasText(xml)) {if (xml.indexOf("errorCode") == -1) {return XmlUtil.getContentFromXml(xml, "accountToken");} else {// 存在错误信息则返回nullreturn null;}} else {return null;}}// 用户登录接口public static boolean login(String username, String password) {return login(username, password, null);}public static boolean login(String username, String password, String userType) {List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>(0);params.add(new BasicNameValuePair("account_token", getToken()));params.add(new BasicNameValuePair("username", username));params.add(new BasicNameValuePair("password", password));if (userType != null) {params.add(new BasicNameValuePair("userType", userType));}String xml = HttpClientUtil.doPost(API_URL + "/login", params);if (!hasText(xml)) {return false;}if (xml.indexOf("errorCode") == -1) {return true;} else {return false;}}private static boolean hasText(String strText) {return strText != null && !"".equals(strText);}}
public static void main(String[] argus) {System.out.println(ApiUtil.getToken());ApiUtil.login("[email protected]", "password");}
请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!
技术博客集 - 网站简介:
前后端技术:
后端基于Hyperf2.1框架开发,前端使用Bootstrap可视化布局系统生成
网站主要作用:
1.编程技术分享及讨论交流,内置聊天系统;
2.测试交流框架问题,比如:Hyperf、Laravel、TP、beego;
3.本站数据是基于大数据采集等爬虫技术为基础助力分享知识,如有侵权请发邮件到站长邮箱,站长会尽快处理;
4.站长邮箱:[email protected];
文章归档
文章标签
友情链接