引數 以query String格式,方法post,傳送http請求
阿新 • • 發佈:2019-02-02
query String格式: http://ip:port?name=zhangsan&pwd=123456
- publicclass APIHttpClient {
- // 介面地址
- privatestatic String apiURL = "http://ip:8080//order";
- private Log logger = LogFactory.getLog(this.getClass());
- privatestaticfinal String pattern = "yyyy-MM-dd HH:mm:ss:SSS";
- private HttpClient httpClient =
- private HttpPost method = null;
- privatelong startTime = 0L;
- privatelong endTime = 0L;
- privateint status = 0;
- /**
- * 介面地址
- *
- * @param url
- */
- public APIHttpClient(String url) {
- if (url != null) {
- this.apiURL = url;
- }
- if
- httpClient = new DefaultHttpClient();
- method = new HttpPost(apiURL);
- }
- }
- /**
- * 呼叫 API
- *
- * @param parameters
- * @return
- */
- public String post(String parameters) {
- String body = null;
- logger.info("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;
- }
- publicstaticvoid 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
- */
- publicint getStatus() {
- return status;
- }
- publicvoid setStatus(int status) {
- this.status = status;
- }
- publiclong getStartTime() {
- return startTime;
- }
- publiclong getEndTime() {
- return endTime;
- }
- }