java如何實現(xiàn)postman中用x-www-form-urlencoded參數(shù)的請求
更新時間:2024年09月29日 09:05:39 作者:黃黃黃黃黃瑩
在Java開發(fā)中,模擬Postman發(fā)送x-www-form-urlencoded類型的請求是一個常見需求,本文主要介紹了如何在Java中實現(xiàn)這一功能,首先,需要通過導(dǎo)入http-client包來創(chuàng)建HTTP客戶端,接著,利用該客戶端發(fā)送Post請求
java postman用x-www-form-urlencoded參數(shù)的請求
首先,先給出postman的參數(shù)構(gòu)造:
java代碼實現(xiàn)(以post方法為例)
PostMethod postMethod = new PostMethod(valueConfig.getImpsAuthUrl()) ; postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8") ; //參數(shù)設(shè)置,需要注意的就是里邊不能傳NULL,要傳空字符串 //key value 形式參數(shù) NameValuePair[] data = { new NameValuePair("username","test"), new NameValuePair("password","test123") }; postMethod.setRequestBody(data); HttpClient httpClient = new HttpClient(); int response = httpClient.executeMethod(postMethod); // 執(zhí)行POST方法 String result = postMethod.getResponseBodyAsString() ; //返回結(jié)果 if (response == 200 && result != null) { //成功后的邏輯 doSth(); log.info("獲取請求,result={}", result); }
java實現(xiàn)postman為x-www-form-urlencoded的調(diào)用
客戶端實現(xiàn)
導(dǎo)入http-client jar。
<dependency> <groupId>commons-httpclient</groupId> <artifactId>commons-httpclient</artifactId> <version>3.1</version> </dependency>
public static void clientDemo() { try { String requestUrl = "http://hello/demo"; PostMethod postMethod = new PostMethod(requestUrl); String data = "json_json_json_json"; StringRequestEntity stringRequestEntity = new StringRequestEntity(data, "application/x-www-form-urlencoded", "utf-8"); postMethod.setRequestEntity(stringRequestEntity); org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient(); //調(diào)用接口 int code = httpClient.executeMethod(postMethod); String result = postMethod.getResponseBodyAsString(); System.out.println("接口狀態(tài)" + code); System.out.println("響應(yīng)" + result); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } }
服務(wù)端實現(xiàn)
@RequestMapping(value = "/receive", method = RequestMethod.POST) @ResponseBody public String receiveFare(@RequestBody String str) { System.out.println("接到數(shù)據(jù):" + str); return "ok"; }
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
springdata jpa使用Example快速實現(xiàn)動態(tài)查詢功能
這篇文章主要介紹了springdata jpa使用Example快速實現(xiàn)動態(tài)查詢功能,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11論Java Web應(yīng)用中調(diào)優(yōu)線程池的重要性
這篇文章主要論述Java Web應(yīng)用中調(diào)優(yōu)線程池的重要性,通過了解應(yīng)用的需求,組合最大線程數(shù)和平均響應(yīng)時間,得出一個合適的線程池配置2016-04-04淺談Mybatis Plus的BaseMapper的方法是如何注入的
我們在用的時候經(jīng)常就是生產(chǎn)自定義的Mapper繼承自BaseMapper,那么BaseMapper怎么被注入到mybatis里的,本文就詳細(xì)的介紹一下,感興趣的可以了解一下2021-09-09深入理解Spring MVC的數(shù)據(jù)轉(zhuǎn)換
這篇文章主要給大家介紹了關(guān)于Spring MVC數(shù)據(jù)轉(zhuǎn)換的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起看看吧。2017-09-09