1. 程式人生 > >java 對接webapi介面資料提交方式之 application/x-www-form-urlencoded

java 對接webapi介面資料提交方式之 application/x-www-form-urlencoded

Content-Type: application/x-www-form-urlencoded;charset=utf-8 

這應該是最常見的 POST 提交資料的方式了。瀏覽器的原生 form 表單,如果不設定 enctype 屬性,那麼最終就會以 application/x-www-form-urlencoded 方式提交資料。 

 

curl 測試介面地址是否通不通,這個命令和postman差不多,比輕量,也會返回請求的結果

curl https://地址  -X POST -d "引數名=引數值&引數名=引數值&引數名=引數值"

加請求格式  application/x-www-form-urlencoded

curl  地址  -X  POST  -H "Content-Type:application/x-www-form-urlencoded" -d "引數名=引數值&引數名=引數值&引數名=引數值"

 

 

 public static String sendxwwwform(String url, Map<String,String> map,String encoding) throws Exception, IOException{
	    	  String body = "";
	          //採用繞過驗證的方式處理https請求
	          SSLContext sslcontext = createIgnoreVerifySSL();
	          
	          // 設定協議http和https對應的處理socket連結工廠的物件
	          Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
	              .register("http", PlainConnectionSocketFactory.INSTANCE)
	              .register("https", new SSLConnectionSocketFactory(sslcontext))
	              .build();
	          PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
	          HttpClients.custom().setConnectionManager(connManager);

	          //建立自定義的httpclient物件
	          CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
	          
	          //建立post方式請求物件
	          HttpPost httpPost = new HttpPost(url);
	          
	          //裝填引數
	          List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
	          if(map!=null){
	              for (Entry<String, String> entry : map.entrySet()) {
	                  nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
	              }
	          }
	          //設定引數到請求物件中
	          httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));

	          System.out.println("請求地址:"+url);
	          System.out.println("請求引數:"+nvps.toString());
	          
	          //設定header資訊
	          //指定報文頭【Content-type】、【User-Agent】
	          httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
	          // httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
	          
	          //執行請求操作,並拿到結果(同步阻塞)
	          CloseableHttpResponse response = client.execute(httpPost);
	          //獲取結果實體
	          HttpEntity entity = response.getEntity();
	          if (entity != null) {
	              //按指定編碼轉換結果實體為String型別
	              body = EntityUtils.toString(entity, encoding);
	          }
	          EntityUtils.consume(entity);
	          //釋放連結
	          response.close();
	          return body;
	    }