Java使用x-www-form-urlencoded發(fā)請(qǐng)求方式
Java使用x-www-form-urlencoded發(fā)請(qǐng)求
平常在開(kāi)發(fā)過(guò)程中用的最多的就是JSON格式,請(qǐng)求編碼就是 application/json
但偏偏有些接口是 x-www-form-urlencoded
怎么辦呢
重新封裝嘍!?。?!
- 在POSTMan工具是叫 x-www-form-urlencoded
- 在 APIpost工具中是叫 urlencoded
Map<String, String> request = new HashMap<>(); request.put("username", "xxx"); request.put("password", "xxx"); String result = HttpRequestUtil.post(request, "http://xxxx", new HashMap<String, String>(), "application/x-www-form-urlencoded"); System.out.println(result);
package utils; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import com.alibaba.fastjson.JSONObject; /** * * @ClassName:HttpRequestUtil * @Description: Http請(qǐng)求 */ public class HttpRequestUtil { private String defaultContentEncoding; public HttpRequestUtil() { this.defaultContentEncoding = Charset.defaultCharset().name(); } /** * 默認(rèn)的響應(yīng)字符集 */ public String getDefaultContentEncoding() { return this.defaultContentEncoding; } /** * 設(shè)置默認(rèn)的響應(yīng)字符集 */ public void setDefaultContentEncoding(String defaultContentEncoding) { this.defaultContentEncoding = defaultContentEncoding; } public static String post(JSONObject json, String url) throws Exception{ CloseableHttpClient httpclient = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(url); CloseableHttpResponse response = null; InputStream in = null; BufferedReader br = null; String result = ""; try { StringEntity s = new StringEntity(json.toString(),"utf-8"); s.setContentEncoding("UTF-8"); /*發(fā)送json數(shù)據(jù)需要設(shè)置contentType*/ s.setContentType("application/json"); post.setEntity(s); post.setHeader("Content-Type","application/json;charset=utf-8"); response = httpclient.execute(post); in = response.getEntity().getContent(); br = new BufferedReader(new InputStreamReader(in, "utf-8")); StringBuilder strber= new StringBuilder(); String line = null; while((line = br.readLine())!=null){ strber.append(line+'\n'); } result = strber.toString(); if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK){ if(StringUtils.isBlank(result)) result = "服務(wù)器異常"; throw new Exception(result); } // System.out.println("返回?cái)?shù)據(jù)="+result); } catch (Exception e) { //System.err.println("調(diào)用接口出錯(cuò)::::::::::::"+e.getMessage()); throw new Exception(e.getMessage()); } finally { if(null != br) br.close(); if(null != br) in.close(); if(null != response) response.close(); if(null != httpclient) httpclient.close(); } return result; } public static String post(JSONObject json, String url, Map<String, String> headerMap) throws Exception{ CloseableHttpClient httpclient = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(url); CloseableHttpResponse response = null; InputStream in = null; BufferedReader br = null; String result = ""; try { StringEntity s = new StringEntity(json.toString(),"utf-8"); s.setContentEncoding("UTF-8"); /*發(fā)送json數(shù)據(jù)需要設(shè)置contentType*/ s.setContentType("application/json"); post.setEntity(s); post.setHeader("Content-Type","application/json;charset=utf-8"); Set<Entry<String, String>> headerEntries = headerMap.entrySet(); for (Entry<String, String> headerEntry:headerEntries){ post.setHeader(headerEntry.getKey(), headerEntry.getValue()); } response = httpclient.execute(post); in = response.getEntity().getContent(); br = new BufferedReader(new InputStreamReader(in, "utf-8")); StringBuilder strber= new StringBuilder(); String line = null; while((line = br.readLine())!=null){ strber.append(line+'\n'); } result = strber.toString(); if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK){ if(StringUtils.isBlank(result)) result = "服務(wù)器異常"; throw new Exception(result); } //System.out.println("返回?cái)?shù)據(jù)="+result); } catch (Exception e) { //System.err.println("調(diào)用接口出錯(cuò)::::::::::::"+e.getMessage()); throw new Exception(e.getMessage()); } finally { br.close(); in.close(); response.close(); httpclient.close(); } return result; } /** * ContentType.URLENCODED.getHeader() * @param map * @param url * @param headerMap * @param contentType * @return * @throws Exception */ public static String post(Map<String, String> map, String url, Map<String, String> headerMap, String contentType) throws Exception{ CloseableHttpClient httpclient = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(url); CloseableHttpResponse response = null; InputStream in = null; BufferedReader br = null; String result = ""; try { List<NameValuePair> nameValuePairs = getNameValuePairList(map); UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairs, "UTF-8"); /*發(fā)送json數(shù)據(jù)需要設(shè)置contentType*/ urlEncodedFormEntity.setContentType(contentType); post.setEntity(urlEncodedFormEntity); post.setHeader("Content-Type", contentType); Set<Entry<String, String>> headerEntries = headerMap.entrySet(); for (Entry<String, String> headerEntry:headerEntries){ post.setHeader(headerEntry.getKey(), headerEntry.getValue()); } response = httpclient.execute(post); in = response.getEntity().getContent(); br = new BufferedReader(new InputStreamReader(in, "utf-8")); StringBuilder strber= new StringBuilder(); String line = null; while((line = br.readLine())!=null){ strber.append(line+'\n'); } result = strber.toString(); if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK){ if(StringUtils.isBlank(result)) result = "服務(wù)器異常"; throw new Exception(result); } //System.out.println("返回?cái)?shù)據(jù)="+result); } catch (Exception e) { //System.err.println("調(diào)用接口出錯(cuò)::::::::::::"+e.getMessage()); throw new Exception(e.getMessage()); } finally { br.close(); in.close(); response.close(); httpclient.close(); } return result; } private static List<NameValuePair> getNameValuePairList(Map<String, String> map) { List<NameValuePair> list = new ArrayList<>(); for(String key : map.keySet()) { list.add(new BasicNameValuePair(key,map.get(key))); } return list; } public static String post(String params, String url, Map<String, String> headerMap) throws Exception{ CloseableHttpClient httpclient = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(url); CloseableHttpResponse response = null; InputStream in = null; BufferedReader br = null; String result = ""; try { StringEntity s = new StringEntity(params.toString(),"utf-8"); s.setContentEncoding("UTF-8"); /*發(fā)送json數(shù)據(jù)需要設(shè)置contentType*/ s.setContentType("application/json"); post.setEntity(s); post.setHeader("Content-Type","application/json;charset=utf-8"); Set<Entry<String, String>> headerEntries = headerMap.entrySet(); for (Entry<String, String> headerEntry:headerEntries){ post.setHeader(headerEntry.getKey(), headerEntry.getValue()); } response = httpclient.execute(post); in = response.getEntity().getContent(); br = new BufferedReader(new InputStreamReader(in, "utf-8")); StringBuilder strber= new StringBuilder(); String line = null; while((line = br.readLine())!=null){ strber.append(line+'\n'); } result = strber.toString(); if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK){ if(StringUtils.isBlank(result)) result = "服務(wù)器異常"; throw new Exception(result); } //System.out.println("返回?cái)?shù)據(jù)="+result); } catch (Exception e) { //System.err.println("調(diào)用接口出錯(cuò)::::::::::::"+e.getMessage()); throw new Exception(e.getMessage()); } finally { br.close(); in.close(); response.close(); httpclient.close(); } return result; } public static String put(JSONObject json, String url, Map<String, String> headerMap) throws Exception { CloseableHttpClient httpclient = HttpClientBuilder.create().build(); HttpPut post = new HttpPut(url); CloseableHttpResponse response = null; InputStream in = null; BufferedReader br = null; String result = ""; try { StringEntity s = new StringEntity(json.toString(),"utf-8"); s.setContentEncoding("UTF-8"); /*發(fā)送json數(shù)據(jù)需要設(shè)置contentType*/ s.setContentType("application/json"); post.setEntity(s); post.setHeader("Content-Type","application/json;charset=utf-8"); Set<Entry<String, String>> headerEntries = headerMap.entrySet(); for (Entry<String, String> headerEntry:headerEntries){ post.setHeader(headerEntry.getKey(), headerEntry.getValue()); } response = httpclient.execute(post); in = response.getEntity().getContent(); br = new BufferedReader(new InputStreamReader(in, "utf-8")); StringBuilder strber= new StringBuilder(); String line = null; while((line = br.readLine())!=null){ strber.append(line+'\n'); } result = strber.toString(); if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK){ if(StringUtils.isBlank(result)) result = "服務(wù)器異常"; throw new Exception(result); } //System.out.println("返回?cái)?shù)據(jù)="+result); } catch (Exception e) { //System.err.println("調(diào)用接口出錯(cuò)::::::::::::"+e.getMessage()); throw new Exception(e.getMessage()); } finally { br.close(); in.close(); response.close(); httpclient.close(); } return result; } public static String delete(String url, Map<String, String> headerMap) throws Exception { CloseableHttpClient httpclient = HttpClientBuilder.create().build(); HttpDelete post = new HttpDelete(url); CloseableHttpResponse response = null; InputStream in = null; BufferedReader br = null; String result = ""; try { post.setHeader("Content-Type","application/json;charset=utf-8"); Set<Entry<String, String>> headerEntries = headerMap.entrySet(); for (Entry<String, String> headerEntry:headerEntries){ post.setHeader(headerEntry.getKey(), headerEntry.getValue()); } response = httpclient.execute(post); in = response.getEntity().getContent(); br = new BufferedReader(new InputStreamReader(in, "utf-8")); StringBuilder strber= new StringBuilder(); String line = null; while((line = br.readLine())!=null){ strber.append(line+'\n'); } result = strber.toString(); if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK){ if(StringUtils.isBlank(result)) result = "服務(wù)器異常"; throw new Exception(result); } //System.out.println("返回?cái)?shù)據(jù)="+result); } catch (Exception e) { //System.err.println("調(diào)用接口出錯(cuò)::::::::::::"+e.getMessage()); throw new Exception(e.getMessage()); } finally { br.close(); in.close(); response.close(); httpclient.close(); } return result; } public static String get(JSONObject paramsObj, String url, Map<String, String> headerMap) throws Exception { CloseableHttpClient httpclient = HttpClientBuilder.create().build(); CloseableHttpResponse response = null; InputStream in = null; BufferedReader br = null; String result = ""; try { StringBuffer param = new StringBuffer(); int i = 0; Set<Entry<String, Object>> entries = paramsObj.entrySet(); for (Entry<String, Object> entry:entries){ if (i == 0) param.append("?"); else param.append("&"); param.append(entry.getKey()).append("=").append(entry.getValue()); i++; } url += param; HttpGet post = new HttpGet(url); // post.setHeader("Content-Type","application/json;charset=utf-8"); Set<Entry<String, String>> headerEntries = headerMap.entrySet(); for (Entry<String, String> headerEntry:headerEntries){ post.setHeader(headerEntry.getKey(), headerEntry.getValue()); } response = httpclient.execute(post); in = response.getEntity().getContent(); br = new BufferedReader(new InputStreamReader(in, "utf-8")); StringBuilder strber= new StringBuilder(); String line = null; while((line = br.readLine())!=null){ strber.append(line+'\n'); } result = strber.toString(); if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK){ if(StringUtils.isBlank(result)) result = "服務(wù)器異常"; throw new Exception(result); } //System.out.println("返回?cái)?shù)據(jù)="+result); } catch (Exception e) { // System.err.println("調(diào)用接口出錯(cuò)::::::::::::"+e.getMessage()); throw new Exception(e.getMessage()); } finally { br.close(); in.close(); response.close(); httpclient.close(); } return result; } }
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java實(shí)現(xiàn)驗(yàn)證文件名有效性的方法詳解
在本文中,我們將討論使用?Java?驗(yàn)證一個(gè)給定的字符串是否具有操作系統(tǒng)的有效文件名的不同方法,文中的示例代碼講解詳細(xì),感興趣的可以了解一下2022-09-09從零開(kāi)始講解Java微信公眾號(hào)消息推送實(shí)現(xiàn)
微信公眾號(hào)分為訂閱號(hào)和服務(wù)號(hào),無(wú)論有沒(méi)有認(rèn)證,訂閱號(hào)每天都能推送一條消息,也就是每天只能推送一次消息給粉絲,這篇文章主要給大家介紹了關(guān)于Java微信公眾號(hào)消息推送實(shí)現(xiàn)的相關(guān)資料,需要的朋友可以參考下2022-09-09Springboot項(xiàng)目Maven依賴沖突的問(wèn)題解決
使用Spring Boot和Maven進(jìn)行項(xiàng)目開(kāi)發(fā)時(shí),依賴沖突是一個(gè)常見(jiàn)的問(wèn)題,本文就來(lái)介紹一下Springboot項(xiàng)目Maven依賴沖突的問(wèn)題解決,具有一定的參考價(jià)值,感興趣的可以了解一下2024-07-07為什么JDK8中HashMap依然會(huì)死循環(huán)
這篇文章主要介紹了為什么JDK8中HashMap依然會(huì)死循環(huán),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09Jax-rs規(guī)范REST接口文件上傳代碼實(shí)例
這篇文章主要介紹了Jax-rs規(guī)范REST接口文件上傳代碼實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-09-09java?數(shù)組越界判斷和獲取數(shù)組長(zhǎng)度的實(shí)現(xiàn)方式
這篇文章主要介紹了java?數(shù)組越界判斷和獲取數(shù)組長(zhǎng)度的實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12解決springboot 2.x 里面訪問(wèn)靜態(tài)資源的坑
這篇文章主要介紹了解決springboot 2.x 里面訪問(wèn)靜態(tài)資源的坑,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-08-08maven繼承父工程統(tǒng)一版本號(hào)的實(shí)現(xiàn)
這篇文章主要介紹了maven繼承父工程統(tǒng)一版本號(hào)的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08Java使用訪問(wèn)者模式解決公司層級(jí)結(jié)構(gòu)圖問(wèn)題詳解
這篇文章主要介紹了Java使用訪問(wèn)者模式解決公司層級(jí)結(jié)構(gòu)圖問(wèn)題,結(jié)合實(shí)例形式分析了訪問(wèn)者模式的概念、原理及Java使用訪問(wèn)者模式解決公司曾經(jīng)結(jié)構(gòu)圖問(wèn)題的相關(guān)操作技巧與注意事項(xiàng),需要的朋友可以參考下2018-04-04