http發送jsonn報文get/post請求

一、第1種方式
1. 因依賴
  <!-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient -->
        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>
2. 工具類+測試方法
package com.gblfy;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;

import java.io.InputStream;
import java.io.InputStreamReader;


public class HTTPUtils {

    /**
     * 協議類型:HTTP
     * 請求方式:POST
     * 報文格式:json
     * 編碼設置:UTF-8
     * 響應類型:jsonStr
     *
     * @param url
     * @param json
     * @return
     * @throws Exception
     */
    public static String postJosnContent(String url, String json) throws Exception {
        System.out.println("請求接口參數:" + json);
        PostMethod method = new PostMethod(url);
        HttpClient httpClient = new HttpClient();
        try {
            RequestEntity entity = new StringRequestEntity(json, "application/json", "UTF-8");
            method.setRequestEntity(entity);
            httpClient.executeMethod(method);
            System.out.println("請求接口路徑url:" + method.getURI().toString());
            InputStream in = method.getResponseBodyAsStream();
            //下面將stream轉換爲String
            StringBuffer sb = new StringBuffer();
            InputStreamReader isr = new InputStreamReader(in, "UTF-8");
            char[] b = new char[4096];
            for (int n; (n = isr.read(b)) != -1; ) {
                sb.append(new String(b, 0, n));
            }
            String returnStr = sb.toString();
            return returnStr;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            method.releaseConnection();
        }
    }

    public static void main(String[] args) throws Exception {
        String url = "http://localhost:8080/httptojson";
        String json = "{\"name\":\"gblfy\"}";
        String res = postJosnContent(url, json);
        System.out.println("響應報文:" + res);
    }
}

3. 服務端接收
package com.gblfy;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
public class AController {

    @RequestMapping(value = "/postToJson", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String postToJson(@RequestBody String json) {
        System.out.println(json);
        return json;
    }
}
二、第2種方式

和第一種方式基本一樣

public static byte[] post(String url, String content, String charset) throws IOException {

        URL console = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) console.openConnection();
        conn.setDoOutput(true);
        // 設置請求頭
        conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
        conn.connect();
        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        out.write(content.getBytes(charset));
        // 刷新、關閉
        out.flush();
        out.close();
        InputStream is = conn.getInputStream();
        if (is != null) {
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = is.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            is.close();
            return outStream.toByteArray();
        }
        return null;
    }
三、第3種方式
3.1. 引依賴
      <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
      <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.9</version>
        </dependency>
3.2. 工具類+測試
package com.gblfy.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.*;

/**
 * @author Mundo
 * @ClassName: HttpClientUtil
 * @Description: TODO
 */

public class HttpApiUtil {
    private static final Logger logger = LoggerFactory.getLogger(HttpApiUtil.class);

    /**
     *
     * @param url 請求路徑
     * @param params 參數
     * @return
     */
    public static String doGet(String url, Map<String, String> params) {

        // 返回結果
        String result = "";
        // 創建HttpClient對象
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet httpGet = null;
        try {
            // 拼接參數,可以用URIBuilder,也可以直接拼接在?傳值,拼在url後面,如下--httpGet = new
            // HttpGet(uri+"?id=123");
            URIBuilder uriBuilder = new URIBuilder(url);
            if (null != params && !params.isEmpty()) {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    uriBuilder.addParameter(entry.getKey(), entry.getValue());
                    // 或者用
                    // 順便說一下不同(setParameter會覆蓋同名參數的值,addParameter則不會)
                    // uriBuilder.setParameter(entry.getKey(), entry.getValue());
                }
            }
            URI uri = uriBuilder.build();
            // 創建get請求
            httpGet = new HttpGet(uri);
            logger.info("訪問路徑:" + uri);
            HttpResponse response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 返回200,請求成功
                // 結果返回
                result = EntityUtils.toString(response.getEntity());
                logger.info("請求成功!,返回數據:" + result);
            } else {
                logger.info("請求失敗!");
            }
        } catch (Exception e) {
            logger.info("請求失敗!");
            logger.error(ExceptionUtils.getStackTrace(e));
        } finally {
            // 釋放連接
            if (null != httpGet) {
                httpGet.releaseConnection();
            }
        }
        return result;
    }

    /**
     * @param url
     * @param params
     * @return
     * @Title: doPost
     * @Description: post請求
     * @author Mundo
     */
    public static String doPost(String url, Map<String, String> params) {
        String result = "";
        // 創建httpclient對象
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);
        try { // 參數鍵值對
            if (null != params && !params.isEmpty()) {
                List<NameValuePair> pairs = new ArrayList<NameValuePair>();
                NameValuePair pair = null;
                for (String key : params.keySet()) {
                    pair = new BasicNameValuePair(key, params.get(key));
                    pairs.add(pair);
                }
                // 模擬表單
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs);
                httpPost.setEntity(entity);
            }
            HttpResponse response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result = EntityUtils.toString(response.getEntity(), "utf-8");
                logger.info("返回數據:>>>" + result);
            } else {
                logger.info("請求失敗!,url:" + url);
            }
        } catch (Exception e) {
            logger.error("請求失敗");
            logger.error(ExceptionUtils.getStackTrace(e));
            e.printStackTrace();
        } finally {
            if (null != httpPost) {
                // 釋放連接
                httpPost.releaseConnection();
            }
        }
        return result;
    }

    /**
     * post發送json字符串
     * @param url
     * @param params
     * @return 返回數據
     * @Title: sendJsonStr
     */
    public static String sendJsonStr(String url, String params) {
        String result = "";

        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);
        try {
            httpPost.addHeader("Content-type", "application/json; charset=utf-8");
            httpPost.setHeader("Accept", "application/json");
            if (StringUtils.isNotBlank(params)) {
                httpPost.setEntity(new StringEntity(params, Charset.forName("UTF-8")));
            }
            HttpResponse response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result = EntityUtils.toString(response.getEntity());
                logger.info("返回數據:" + result);
            } else {
                logger.info("請求失敗");
            }
        } catch (IOException e) {
            logger.error("請求異常");
            logger.error(ExceptionUtils.getStackTrace(e));
        }
        return result;
    }

    /**
     * 發送http請求的obj報文(內置轉json)
     *
     * @param url
     * @param obj
     * @return
     */
    public static String postJson(String url, Object obj) {
        HttpURLConnection conn = null;
        try {
            // 創建一個URL對象
            URL mURL = new URL(url);
            // 調用URL的openConnection()方法,獲取HttpURLConnection對象
            conn = (HttpURLConnection) mURL.openConnection();
            conn.setRequestMethod("POST");// 設置請求方法爲post
           /* conn.setReadTimeout(5000);// 設置讀取超時爲5秒
            conn.setConnectTimeout(10000);// 設置連接網絡超時爲10秒*/
            conn.setDoOutput(true);// 設置此方法,允許向服務器輸出內容
            // 設置文件類型:
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            // 設置接收類型否則返回415錯誤
            conn.setRequestProperty("accept", "application/json");
            int len = 0;
            // post請求的參數
            byte[] buf = new byte[10240];
            //
            String data = JSONObject.toJSONString(obj);

            // 獲得一個輸出流,向服務器寫數據,默認情況下,系統不允許向服務器輸出內容
            OutputStream out = conn.getOutputStream();// 獲得一個輸出流,向服務器寫數據
            out.write(data.getBytes());
            out.flush();
            out.close();

            int responseCode = conn.getResponseCode();// 調用此方法就不必再使用conn.connect()方法
            if (responseCode == 200) {
                InputStream is = conn.getInputStream();
                String state = getStringFromInputStream(is);
                return state;
            } else {
                System.out.print("訪問失敗" + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();// 關閉連接
            }
        }
        return null;
    }

    public static String getStringFromInputStream(InputStream is) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        // 模板代碼 必須熟練
        byte[] buffer = new byte[1024];
        int len = -1;
        // 一定要寫len=is.read(buffer)
        // 如果while((is.read(buffer))!=-1)則無法將數據寫入buffer中
        while ((len = is.read(buffer)) != -1) {
            os.write(buffer, 0, len);
        }
        is.close();
        String state = os.toString();// 把流中的數據轉換成字符串,採用的編碼是utf-8(模擬器默認編碼)
        os.close();
        return state;
    }

    /**
     * post方式請求服務器(http協議)
     *
     * @param url     請求地址
     * @param content 參數
     * @param charset 編碼
     * @return
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     * @throws IOException
     */
    public static byte[] post(String url, String content, String charset) throws IOException {

        URL console = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) console.openConnection();
        conn.setDoOutput(true);
        // 設置請求頭
        conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
        conn.connect();
        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        out.write(content.getBytes(charset));
        // 刷新、關閉
        out.flush();
        out.close();
        InputStream is = conn.getInputStream();
        if (is != null) {
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = is.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            is.close();
            return outStream.toByteArray();
        }
        return null;
    }
    
    public static void main(String[] args) {
        //測試1 get發送map
        Map<String, String> map = new HashMap<String, String>();
        map.put("id", UUID.randomUUID().toString());
        map.put("name", "gblfy");
        String get = doGet("http://localhost:8080/getToMap", map);
        System.out.println("get請求調用成功,返回數據是:" + get);

        //測試2 post發送map
        // String post = doPost("http://localhost:8080/httptojson", map);
        // System.out.println("post調用成功,返回數據是:" + post);

        //測試3 post發送json字符串
        // String json = sendJsonStr("http://localhost:8080/httptojson", "{\"name\":\"ly\"}");
        // System.out.println("json發送成功,返回數據是:" + json);

         //測試4 post發送obj對象
        // User user = new User();
        // user.setUsername("POST_JSON");
        // user.setAge(12);
        // user.setPasswd("00990099");
        // String json = postJson("http://localhost:8080/httptojson", user);
        // System.out.println("json發送成功,返回數據是:" + json);

    }
}


3.3. 服務端代碼
package com.gblfy;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
public class AController {

    @RequestMapping(value = "/postToJson", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String postToJson(@RequestBody String json) {
        System.out.println(json);
        return json;
    }

    @RequestMapping(value = "/getToMap", method = RequestMethod.GET)
    public String getToMap(@RequestParam(name = "id") String id,
                           @RequestParam(name = "name") String name) {
        System.out.println(id);
        System.out.println(name);
        StringBuffer buf = new StringBuffer();
        buf.append(id);
        buf.append(name);
        return buf.toString();
    }
}

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