远程接口调用——测试类

package com.zichen.test;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

public class OrderAndroidTest {

	private static final Logger log = LoggerFactory
			.getLogger(OrderAndroidTest.class);

	@Test
	public void test() throws Exception {

		JSONObject requestJSONStr = new JSONObject();
		JSONObject publicData = new JSONObject();
		JSONObject requestData = new JSONObject();

		publicData.put("sn", "1234567890");
		requestJSONStr.put("publicData", publicData);

		Map<String, Object> order = new HashMap<String, Object>();
		order.put("storeId", 123);
		order.put("storeName", "柱子");
		order.put("totalMoney", new BigDecimal(200));
		order.put("userTelephone", 123456);
		order.put("remark", "测试");

		List<Map<String, Object>> orderDetailsList = new ArrayList<Map<String, Object>>();
		Map<String, Object> orderDetails = new HashMap<String, Object>();
		orderDetails.put("goodsId", 1);
		orderDetails.put("goodsName", "烧饭");
		orderDetails.put("goodsPicture", null);
		orderDetails.put("goodsCount", 2);
		orderDetails.put("itemPricing", 100);
		orderDetails.put("goodsPrice", 200);
		orderDetails.put("specificationId", 5);
		orderDetails.put("specificationName", "不要辣");

		Map<String, Object> orderDetails2 = new HashMap<String, Object>();
		orderDetails2.put("goodsId", 2);
		orderDetails2.put("goodsName", "嫂子面");
		orderDetails2.put("goodsPicture", null);
		orderDetails2.put("goodsCount", 1);
		orderDetails2.put("itemPricing", 200);
		orderDetails2.put("goodsPrice", 200);
		orderDetails2.put("specificationId", 5);
		orderDetails2.put("specificationName", "不要辣");

		orderDetailsList.add(orderDetails);
		orderDetailsList.add(orderDetails2);

		requestData.put("listOrderDetails", orderDetailsList);
		requestData.put("orderAndroid", order);

		requestJSONStr.put("requestData", requestData);

		Map<String, String> map = new HashMap<String, String>();

		map.put("requestJSONStr", requestJSONStr.toJSONString());

		// 测试检测版本信息接口
		String resStr = OrderAndroidTest.httpRequest(
				"http://127.0.0.1/handordering/AndroidOrderManage/createOrder",
				"POST", OrderAndroidTest.transParameter(map));
		System.err.println(resStr);
	}

	/**
	 * 请求参数转化
	 * 
	 * @param map
	 * @return
	 * @throws Exception
	 */
	public static String transParameter(Map<String, String> map)
			throws Exception {
		StringBuffer sb = new StringBuffer();
		for (Map.Entry<String, String> entry : map.entrySet()) {
			sb.append(entry.getKey()).append("=");
			sb.append(URLEncoder.encode(entry.getValue(), "UTF-8")).append("&");
		}
		return sb.toString();
	}

	/**
	 * 发起http或https请求并获取结果
	 * 
	 * @param requestUrl
	 *            请求地址
	 * @param requestMethod
	 *            请求方式(GET、POST)
	 * @param outputStr
	 *            提交的数据
	 * 
	 */
	public static String httpRequest(String requestUrl, String requestMethod,
			String outputStr) {
		log.info("接收的参数:" + requestUrl + "," + requestMethod + "," + outputStr);

		StringBuffer buffer = new StringBuffer();
		try {
			URL url = new URL(requestUrl);
			HttpURLConnection httpUrlConn = (HttpURLConnection) url
					.openConnection();

			log.info("httpUrlConn:" + httpUrlConn);

			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);

			httpUrlConn.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");

			// 设置请求方式(GET/POST)
			httpUrlConn.setRequestMethod(requestMethod);

			if ("GET".equalsIgnoreCase(requestMethod)) {
				httpUrlConn.connect();
				log.info("get请求");

			}

			// 当有数据需要提交时
			if (null != outputStr && !"".equals(outputStr)) {
				log.info("========================================");
				OutputStream outputStream = httpUrlConn.getOutputStream();
				// 注意编码格式,防止中文乱码
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.flush();
				outputStream.close();
			}
			int A = HttpURLConnection.HTTP_OK;
			int B = httpUrlConn.getResponseCode();
			if (HttpURLConnection.HTTP_OK != httpUrlConn.getResponseCode()) {
				System.out.println("httpUrlConn.getResponseCode():"
						+ httpUrlConn.getResponseCode());
			}
			if (HttpURLConnection.HTTP_OK != httpUrlConn.getResponseCode()) {
				System.out.println("httpUrlConn.getResponseCode():"
						+ httpUrlConn.getResponseCode());
			}

			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(
					inputStream, "UTF-8");
			BufferedReader bufferedReader = new BufferedReader(
					inputStreamReader);

			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
			return buffer.toString();
		} catch (ConnectException ce) {
			// log.error("server connection timed out.");
			System.out.println(ce.getMessage());
		} catch (Exception e) {
			System.out.println(e.getMessage());
			// log.error("https request error:{}", e);
		}
		return null;
	}

}

猜你喜欢

转载自blog.csdn.net/xinpz/article/details/88183912