Java POST(x-www-form-urlencoded)請求
平時都是喜歡用JSON,這種也是第一次。這兩種的區(qū)別就是傳遞參數(shù)類型不一樣。廢話不多說,直接上代碼
1、引入maven包
<dependency> <groupId>commons-httpclient</groupId> <artifactId>commons-httpclient</artifactId> <version>3.1</version> </dependency>
2、代碼實(shí)現(xiàn)
try { String postURL PostMethod postMethod = null; postMethod = new PostMethod(postURL) ; postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8") ; //參數(shù)設(shè)置,需要注意的就是里邊不能傳NULL,要傳空字符串 NameValuePair[] data = { new NameValuePair("startTime",""), new NameValuePair("endTime","") }; postMethod.setRequestBody(data); org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient(); int response = httpClient.executeMethod(postMethod); // 執(zhí)行POST方法 String result = postMethod.getResponseBodyAsString() ; return result; } catch (Exception e) { logger.info("請求異常"+e.getMessage(),e); throw new RuntimeException(e.getMessage()); }
3、POSTMAN參數(shù)組裝
使用post 請求x-www-form-urlencoded格式數(shù)據(jù)
代碼如下:
public String getMsg() { String result = ""; try { URL url = new URL("https://XXXX.cn/token"); //通過調(diào)用url.openConnection()來獲得一個新的URLConnection對象,并且將其結(jié)果強(qiáng)制轉(zhuǎn)換為HttpURLConnection. HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("POST"); //設(shè)置連接的超時值為30000毫秒,超時將拋出SocketTimeoutException異常 urlConnection.setConnectTimeout(30000); //設(shè)置讀取的超時值為30000毫秒,超時將拋出SocketTimeoutException異常 urlConnection.setReadTimeout(30000); //將url連接用于輸出,這樣才能使用getOutputStream()。getOutputStream()返回的輸出流用于傳輸數(shù)據(jù) urlConnection.setDoOutput(true); //設(shè)置通用請求屬性為默認(rèn)瀏覽器編碼類型 urlConnection.setRequestProperty("content-type", "application/x-www-form-urlencoded"); //getOutputStream()返回的輸出流,用于寫入?yún)?shù)數(shù)據(jù)。 OutputStream outputStream = urlConnection.getOutputStream(); String content = "grant_type=password&app_key="+APP_KEY+"&app_secret="+APP_SECRET; outputStream.write(content.getBytes()); outputStream.flush(); outputStream.close(); //此時將調(diào)用接口方法。getInputStream()返回的輸入流可以讀取返回的數(shù)據(jù)。 InputStream inputStream = urlConnection.getInputStream(); byte[] data = new byte[1024]; StringBuilder sb = new StringBuilder(); //inputStream每次就會將讀取1024個byte到data中,當(dāng)inputSteam中沒有數(shù)據(jù)時,inputStream.read(data)值為-1 while (inputStream.read(data) != -1) { String s = new String(data, Charset.forName("utf-8")); sb.append(s); } result = sb.toString(); inputStream.close(); } catch (IOException e) { e.printStackTrace(); } return result; }
以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/Commander_Officer/article/details/86471664