http post(json,xml)

package com.ucmed.hnust.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.log4j.Logger;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by ZY-LJ-1446 on 2018/4/18.
 */
public class HttpRequestPost {
    private static final Logger logger = Logger.getLogger(HttpRequestPost.class);

    public static JSONObject HttpRequest(String requestUrl, String requestMethod,
                                         String outputStr) {
        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        OutputStream out = null;
        InputStream input = null;
        InputStreamReader inputReader = null;
        BufferedReader reader = null;
        HttpURLConnection connection = null;
        try {
            // 建立連接
            URL url = new URL(requestUrl);
            connection = (HttpURLConnection) url.openConnection();
			// 設置通用的請求屬性 start  看需要自行增加和刪除
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
//            conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            conn.setRequestProperty("Accept-Charset", "UTF-8");
            conn.setRequestProperty("contentType", "UTF-8");
            conn.setRequestProperty("Accept-Language", Locale.getDefault().toString());
			// 設置通用的請求屬性 end
            // 設置http頭部信息
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setRequestMethod(requestMethod);
            connection.setConnectTimeout(6000);
            connection.setReadTimeout(6000);
            // 寫入消息實體
            if (outputStr != null) {
                out = connection.getOutputStream();
                out.write(outputStr.getBytes("UTF-8"));
            }
			 // flush輸出流的緩衝
            out.flush();
			
            // 流處理
            input = connection.getInputStream();
            inputReader = new InputStreamReader(input, "UTF-8");
            reader = new BufferedReader(inputReader);
			
			// 方式二 start
			//reader = new BufferedReader(new InputStreamReader(
            //      conn.getInputStream(), "UTF-8"));
			// 方式二 end
			
            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            jsonObject = JSONObject.parseObject(buffer.toString());
        } catch (Exception e) {
            //日誌處理等,請自行實現
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (input != null) {
                    input.close();
                }
                if (reader != null) {
                    reader.close();
                }
                if (inputReader != null) {
                    inputReader.close();
                }
                if (connection != null)
                {
                    connection.disconnect();
                }
            } catch (Exception e) {
                //日誌處理等,請自行實現
                logger.info(e.toString());
            }
        }
        return jsonObject;
    }


    /**
     * post請求(用於請求json格式的參數) 廢棄
     * @param url
     * @param params
     * @return
     */
    /*public static String doPost(String url, String params) throws Exception {

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);// 創建httpPost
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-Type", "application/json");
        String charSet = "UTF-8";
        StringEntity entity = new StringEntity(params, charSet);
        httpPost.setEntity(entity);
        CloseableHttpResponse response = null;

        try {

            response = httpclient.execute(httpPost);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                String jsonString = EntityUtils.toString(responseEntity);
                return jsonString;
            }
            else{
                logger.error("請求返回:"+state+"("+url+")");
            }
        }
        finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }*/
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章