http发送jsonn报文get/post请求
生活随笔
收集整理的這篇文章主要介紹了
http发送jsonn报文get/post请求
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
文章目錄
- 一、第1種方式
- 1. 因依賴
- 2. 工具類+測試方法
- 3. 服務(wù)端接收
- 二、第2種方式
- 三、第3種方式
- 3.1. 引依賴
- 3.2. 工具類+測試
- 3.3. 服務(wù)端代碼
一、第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 {/*** 協(xié)議類型:HTTP* 請(qǐng)求方式:POST* 報(bào)文格式:json* 編碼設(shè)置:UTF-8* 響應(yīng)類型:jsonStr** @param url* @param json* @return* @throws Exception*/public static String postJosnContent(String url, String json) throws Exception {System.out.println("請(qǐng)求接口參數(shù):" + 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("請(qǐng)求接口路徑url:" + method.getURI().toString());InputStream in = method.getResponseBodyAsStream();//下面將stream轉(zhuǎn)換為StringStringBuffer 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("響應(yīng)報(bào)文:" + res);} }3. 服務(wù)端接收
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")@ResponseBodypublic 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);// 設(shè)置請(qǐng)求頭conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");conn.connect();DataOutputStream out = new DataOutputStream(conn.getOutputStream());out.write(content.getBytes(charset));// 刷新、關(guān)閉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 請(qǐng)求路徑* @param params 參數(shù)* @return*/public static String doGet(String url, Map<String, String> params) {// 返回結(jié)果String result = "";// 創(chuàng)建HttpClient對(duì)象HttpClient httpClient = HttpClientBuilder.create().build();HttpGet httpGet = null;try {// 拼接參數(shù),可以用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會(huì)覆蓋同名參數(shù)的值,addParameter則不會(huì))// uriBuilder.setParameter(entry.getKey(), entry.getValue());}}URI uri = uriBuilder.build();// 創(chuàng)建get請(qǐng)求httpGet = new HttpGet(uri);logger.info("訪問路徑:" + uri);HttpResponse response = httpClient.execute(httpGet);if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 返回200,請(qǐng)求成功// 結(jié)果返回result = EntityUtils.toString(response.getEntity());logger.info("請(qǐng)求成功!,返回?cái)?shù)據(jù):" + result);} else {logger.info("請(qǐng)求失敗!");}} catch (Exception e) {logger.info("請(qǐng)求失敗!");logger.error(ExceptionUtils.getStackTrace(e));} finally {// 釋放連接if (null != httpGet) {httpGet.releaseConnection();}}return result;}/*** @param url* @param params* @return* @Title: doPost* @Description: post請(qǐng)求* @author Mundo*/public static String doPost(String url, Map<String, String> params) {String result = "";// 創(chuàng)建httpclient對(duì)象HttpClient httpClient = HttpClientBuilder.create().build();HttpPost httpPost = new HttpPost(url);try { // 參數(shù)鍵值對(duì)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("返回?cái)?shù)據(jù):>>>" + result);} else {logger.info("請(qǐng)求失敗!,url:" + url);}} catch (Exception e) {logger.error("請(qǐng)求失敗");logger.error(ExceptionUtils.getStackTrace(e));e.printStackTrace();} finally {if (null != httpPost) {// 釋放連接httpPost.releaseConnection();}}return result;}/*** post發(fā)送json字符串* @param url* @param params* @return 返回?cái)?shù)據(jù)* @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("返回?cái)?shù)據(jù):" + result);} else {logger.info("請(qǐng)求失敗");}} catch (IOException e) {logger.error("請(qǐng)求異常");logger.error(ExceptionUtils.getStackTrace(e));}return result;}/*** 發(fā)送http請(qǐng)求的obj報(bào)文(內(nèi)置轉(zhuǎn)json)** @param url* @param obj* @return*/public static String postJson(String url, Object obj) {HttpURLConnection conn = null;try {// 創(chuàng)建一個(gè)URL對(duì)象URL mURL = new URL(url);// 調(diào)用URL的openConnection()方法,獲取HttpURLConnection對(duì)象conn = (HttpURLConnection) mURL.openConnection();conn.setRequestMethod("POST");// 設(shè)置請(qǐng)求方法為post/* conn.setReadTimeout(5000);// 設(shè)置讀取超時(shí)為5秒conn.setConnectTimeout(10000);// 設(shè)置連接網(wǎng)絡(luò)超時(shí)為10秒*/conn.setDoOutput(true);// 設(shè)置此方法,允許向服務(wù)器輸出內(nèi)容// 設(shè)置文件類型:conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");// 設(shè)置接收類型否則返回415錯(cuò)誤conn.setRequestProperty("accept", "application/json");int len = 0;// post請(qǐng)求的參數(shù)byte[] buf = new byte[10240];//String data = JSONObject.toJSONString(obj);// 獲得一個(gè)輸出流,向服務(wù)器寫數(shù)據(jù),默認(rèn)情況下,系統(tǒng)不允許向服務(wù)器輸出內(nèi)容OutputStream out = conn.getOutputStream();// 獲得一個(gè)輸出流,向服務(wù)器寫數(shù)據(jù)out.write(data.getBytes());out.flush();out.close();int responseCode = conn.getResponseCode();// 調(diào)用此方法就不必再使用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();// 關(guān)閉連接}}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)則無法將數(shù)據(jù)寫入buffer中while ((len = is.read(buffer)) != -1) {os.write(buffer, 0, len);}is.close();String state = os.toString();// 把流中的數(shù)據(jù)轉(zhuǎn)換成字符串,采用的編碼是utf-8(模擬器默認(rèn)編碼)os.close();return state;}/*** post方式請(qǐng)求服務(wù)器(http協(xié)議)** @param url 請(qǐng)求地址* @param content 參數(shù)* @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);// 設(shè)置請(qǐng)求頭conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");conn.connect();DataOutputStream out = new DataOutputStream(conn.getOutputStream());out.write(content.getBytes(charset));// 刷新、關(guān)閉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發(fā)送mapMap<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請(qǐng)求調(diào)用成功,返回?cái)?shù)據(jù)是:" + get);//測試2 post發(fā)送map// String post = doPost("http://localhost:8080/httptojson", map);// System.out.println("post調(diào)用成功,返回?cái)?shù)據(jù)是:" + post);//測試3 post發(fā)送json字符串// String json = sendJsonStr("http://localhost:8080/httptojson", "{\"name\":\"ly\"}");// System.out.println("json發(fā)送成功,返回?cái)?shù)據(jù)是:" + json);//測試4 post發(fā)送obj對(duì)象// 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發(fā)送成功,返回?cái)?shù)據(jù)是:" + json);} }3.3. 服務(wù)端代碼
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")@ResponseBodypublic 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();} }總結(jié)
以上是生活随笔為你收集整理的http发送jsonn报文get/post请求的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 前后端敏感数据加密方案及实现_03
- 下一篇: mybatis:在springboot中