HttpClient通過Post方式發送Json數據

服務器用的是Springmvc,接口內容:

	@ResponseBody
	@RequestMapping(value="/order",method=RequestMethod.POST)
	public boolean order(HttpServletRequest request,@RequestBody List<Order> orders) throws Exception {
		AdmPost admPost = SessionUtil.getCurrentAdmPost(request);
		if(admPost == null){
			throw new RuntimeException("[OrderController-saveOrUpdate()] 當前登陸的用戶職務信息不能爲空!");
		}
		try {
			this.orderService.saveOrderList(orders,admPost);
			Loggers.log("訂單管理",admPost.getId(),"導入",new Date(),"導入訂單成功,訂單信息--> " + GsonUtil.toString(orders, new TypeToken<List<Order>>() {}.getType()));
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.log("訂單管理",admPost.getId(),"導入",new Date(),"導入訂單失敗,訂單信息--> " + GsonUtil.toString(orders, new TypeToken<List<Order>>() {}.getType()));
			return false;
		}
	}

通過ajax訪問的時候,代碼如下:

                     $.ajax({
				type : "POST",
				contentType : "application/json; charset=utf-8",
				url : ctx + "order/saveOrUpdate",
				dataType : "json",
				anysc : false,
				data : {orders:[{orderId:"11",createTimeOrder:"2015-08-11"}]},  // Post 方式,data參數不能爲空"",如果不傳參數,也要寫成"{}",否則contentType將不能附加在Request Headers中。
				success : function(data){
					if (data != undefined && $.parseJSON(data) == true){
						$.messager.show({
							title:'提示信息',
							msg:'保存成功!',
							timeout:5000,
							showType:'slide'
						});
					}else{
						$.messager.alert('提示信息','保存失敗!','error');
					}
				},
				error : function(XMLHttpRequest, textStatus, errorThrown) {
					alert(errorThrown + ':' + textStatus); // 錯誤處理
				}
			});

通過HttpClient方式訪問,代碼如下:


package com.ec.spring.test;

import java.io.IOException;
import java.nio.charset.Charset;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

public class APIHttpClient {

	// 接口地址
	private static String apiURL = "http://192.168.3.67:8080/lkgst_manager/order/order";
	private Log logger = LogFactory.getLog(this.getClass());
	private static final String pattern = "yyyy-MM-dd HH:mm:ss:SSS";
	private HttpClient httpClient = null;
	private HttpPost method = null;
	private long startTime = 0L;
	private long endTime = 0L;
	private int status = 0;

	/**
	 * 接口地址
	 * 
	 * @param url
	 */
	public APIHttpClient(String url) {

		if (url != null) {
			this.apiURL = url;
		}
		if (apiURL != null) {
			httpClient = new DefaultHttpClient();
			method = new HttpPost(apiURL);

		}
	}

	/**
	 * 調用 API
	 * 
	 * @param parameters
	 * @return
	 */
	public String post(String parameters) {
		String body = null;
		logger.info("parameters:" + parameters);

		if (method != null & parameters != null
				&& !"".equals(parameters.trim())) {
			try {

				// 建立一個NameValuePair數組,用於存儲欲傳送的參數
				method.addHeader("Content-type","application/json; charset=utf-8");
				method.setHeader("Accept", "application/json");
				method.setEntity(new StringEntity(parameters, Charset.forName("UTF-8")));
				startTime = System.currentTimeMillis();

				HttpResponse response = httpClient.execute(method);
				
				endTime = System.currentTimeMillis();
				int statusCode = response.getStatusLine().getStatusCode();
				
				logger.info("statusCode:" + statusCode);
				logger.info("調用API 花費時間(單位:毫秒):" + (endTime - startTime));
				if (statusCode != HttpStatus.SC_OK) {
					logger.error("Method failed:" + response.getStatusLine());
					status = 1;
				}

				// Read the response body
				body = EntityUtils.toString(response.getEntity());

			} catch (IOException e) {
				// 網絡錯誤
				status = 3;
			} finally {
				logger.info("調用接口狀態:" + status);
			}

		}
		return body;
	}

	public static void main(String[] args) {
		APIHttpClient ac = new APIHttpClient(apiURL);
		JsonArray arry = new JsonArray();
		JsonObject j = new JsonObject();
		j.addProperty("orderId", "中文");
		j.addProperty("createTimeOrder", "2015-08-11");
		arry.add(j);
		System.out.println(ac.post(arry.toString()));
	}

	/**
	 * 0.成功 1.執行方法失敗 2.協議錯誤 3.網絡錯誤
	 * 
	 * @return the status
	 */
	public int getStatus() {
		return status;
	}

	/**
	 * @param status
	 *            the status to set
	 */
	public void setStatus(int status) {
		this.status = status;
	}

	/**
	 * @return the startTime
	 */
	public long getStartTime() {
		return startTime;
	}

	/**
	 * @return the endTime
	 */
	public long getEndTime() {
		return endTime;
	}
}



發佈了146 篇原創文章 · 獲贊 50 · 訪問量 239萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章