1. 程式人生 > >httpClient傳送post請求的demo

httpClient傳送post請求的demo

/**
 * 	傳送HttpClient
 * 
 */
public class HttpClientTest {

	public static void main(String[] args) throws IOException {
		delete();
	}

	public static void query() throws IOException {

		CloseableHttpClient client = HttpClientBuilder.create().build();

		HttpPost post = new HttpPost(
				"http://localhost:7001/pa18shoplife/lifegame/ItemareaBag/query.do3");

		Map<String, Object> map = new HashMap<String, Object>();
		List<String> list = new ArrayList<String>();
		list.add("41");
		list.add("42");
		map.put("ids", list);
		map.put("pageNumber", "1");
		map.put("pageSize", "5000");
		String str = Utils.convertToString4Obj(map);
		System.out.println(str);

		respCallback(client, post, str);
	}

	public static void saveorupdate() throws IOException,
			UnsupportedEncodingException, ClientProtocolException {
		CloseableHttpClient client = HttpClientBuilder.create().build();

		HttpPost post = new HttpPost(
				"http://localhost:7001/pa18shoplife/lifegame/ItemareaBag/saveorupdate.do3");

		List<LifeGameItemareaBagDTO> list = new ArrayList<LifeGameItemareaBagDTO>();

		LifeGameItemareaBagDTO dto = new LifeGameItemareaBagDTO();
		dto.setId(41);
		dto.setRoleId(3);
		dto.setGridbag("11111");
		dto.setGridnum(3);
		list.add(dto);

		dto = new LifeGameItemareaBagDTO();
		dto.setId(42);
		dto.setRoleId(4);
		dto.setGridbag("222222");
		dto.setGridnum(3);
		list.add(dto);

		String jsonStr = JSON.json(list);
		System.out.println(jsonStr);
		respCallback(client, post, jsonStr);
	}

	public static void delete() throws IOException,
			UnsupportedEncodingException, ClientProtocolException {
		CloseableHttpClient client = HttpClientBuilder.create().build();

		HttpPost post = new HttpPost(
				"http://localhost:7001/pa18shoplife/lifegame/ItemareaBag/delete.do3");
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

		Map<String, Object> map1 = new HashMap<String, Object>();
		map1.put("id", "41");

		Map<String, Object> map2 = new HashMap<String, Object>();
		map2.put("id", "42");

		list.add(map1);
		list.add(map2);

		String str = Utils.convertToString4Obj(list);
		System.out.println(str);
		respCallback(client, post, str);
	}

	private static void respCallback(CloseableHttpClient client, HttpPost post,
			String str) throws IOException {
		post.setEntity(new StringEntity(str, "utf-8"));

		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		InputStream ins = null;
		try {
			CloseableHttpResponse resp = client.execute(post);
			if (resp.getStatusLine().getStatusCode() == 200) {
				ins = resp.getEntity().getContent();
				IOUtils.copy(ins, bos);
				System.out.println(new String(bos.toByteArray(), "UTF-8"));
			} else {
				System.out.println("error..............");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(ins);
			IOUtils.closeQuietly(bos);
			client.close();
		}
	}

}

/**
 * 物品區域 --> 揹包
 * 
 */
public class LifeGameItemareaBagDTO {

	private long id;
	private long roleId;
	private String gridbag;
	private int gridnum;

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public long getRoleId() {
		return roleId;
	}

	public void setRoleId(long roleId) {
		this.roleId = roleId;
	}

	public String getGridbag() {
		return gridbag;
	}

	public void setGridbag(String gridbag) {
		this.gridbag = gridbag;
	}

	public int getGridnum() {
		return gridnum;
	}

	public void setGridnum(int gridnum) {
		this.gridnum = gridnum;
	}

}

/**
 * 	專用工具類
 * 
 */
public class Utils {
	
	private static final Logger logger = LoggerFactory.getLogger(Utils.class);
	
	/**
	 * @param obj
	 * @return 返回JSON字串
	 */
	public static <T> String convertToString4Obj(T obj){
		
		try {
			return JSON.json(obj);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "{\"resultCode\":-500,\"msg\":\"不能把Obj變為JSON字串.\"}";
	}

	/**
	 * @param clazz
	 * @param req
	 * @return
	 * @throws Exception
	 * 
	 * 根據請求的request 的 body 返回 clazz的list形式
	 */
	public static <T> List<T> convertToListObject(Class<T> clazz,
			HttpServletRequest req) throws Exception{
		return convertToListObject(clazz, toString(req));
	}

	/**
	 * @param clazz
	 * @param jsonStr
	 * @return
	 * 
	 * 根據字串返回clazz的list形式
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static <T> List<T> convertToListObject(Class<T> clazz, String jsonStr)
			throws Exception{
		List<T> retVal = new ArrayList<T>();
		if(StringUtils.isBlank(jsonStr)){
			return retVal;
		}
		try {
			Object obj = JSON.parse(jsonStr);
			if (obj instanceof JSONArray) {
				List<Map> list = JSON.parse(jsonStr, List.class);
				if(clazz == Map.class){
					return (List<T>) list;
				}
				for (Map<String, Object> map : list) {
					T t = clazz.newInstance();
					BeanUtils.copyProperties(t, map);
					retVal.add(t);
				}
			} else if (obj instanceof JSONObject) {
				Map map = JSON.parse(jsonStr, Map.class);
				if(clazz == Map.class){
					retVal.add((T) map);
					return retVal;
				}
				T t = clazz.newInstance();
				BeanUtils.copyProperties(t, map);
				retVal.add(t);
			}
		} catch (ParseException e) {
			logger.info("parse JSON error.......",e);
			throw e;
		} catch (InstantiationException e) {
			logger.info("instance clazz[{}] error.......",clazz,e);
			throw e;
		} catch (IllegalAccessException e) {
			logger.info("IllegalAccessException........",e);
			throw e;
		} catch (InvocationTargetException e) {
			logger.info("InvocationTargetException........",e);
			throw e;
		}
		return retVal;
	}

	/**
	 * @param req
	 * @return
	 * @throws IOException
	 * 
	 * 返回req的body字串
	 */
	public static String toString(HttpServletRequest req) throws IOException {
		ByteArrayOutputStream writer = new ByteArrayOutputStream();
		InputStream ins = null;
		String retVal = null;
		try {
			ins = req.getInputStream();
			if (ins != null) {
				IOUtils.copy(ins, writer);
				retVal = new String(writer.toByteArray(),"utf-8");
			}
		} finally {
			IOUtils.closeQuietly(ins);
			IOUtils.closeQuietly(writer);
		}
		logger.info("request body is [{}]",retVal);
		return retVal;
	}

	/**
	 * @param req
	 * @return
	 * @throws IOException 
	 * 
	 */
	@SuppressWarnings("rawtypes")
	public static Map convertToMap(HttpServletRequest req) throws Exception {
		String jsonStr = toString(req);
		if(StringUtils.isNotBlank(jsonStr)){
			return JSON.parse(jsonStr, Map.class);
		}
		return null;
	}

}

相關jar包:

commons-beanutils.jar
commons-collections-3.1.jar
commons-io-1.4.jar
commons-lang.jar
commons-logging.jar
dubbo-2.4.9.1.jar
httpclient-4.3.6.jar
httpcore-4.3.3.jar
javaee.jar
javassist-3.16.1-GA.jar
log4j-1.2.15.jar
slf4j-api-1.7.2.jar
slf4j-log4j12-1.7.2.jar