HttpClient模擬x-www-form-urlencoded格式的form表單提交


form表單提交的時候,是x-www-form-urlencoded 格式,此時如果用HttpClient類去做,代碼應該是這樣:

 
         
import com.gewara.util.HttpResult;
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.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

//
組織參數 TreeMap<String, String> treeMapParams = new TreeMap<>(); treeMapParams.put("username", "xx"); List<NameValuePair> nameValuePairList = OpenapiParamsUtil.buildNameValuePairList(treeMapParams); // 設置參數 HttpPost httpPost = new HttpPost(HttpUtil.LOCK_COUPON_URL); UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList, "UTF-8"); httpPost.setEntity(urlEncodedFormEntity); HttpResult httpResult = null; try( CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = httpClient.execute(httpPost); ){ httpResult = HttpUtil.dealResponse(response); String result = httpResult.getResponse(); logger.info("result ============= " + result); return result; } catch (Exception e){ logger.error(e.getMessage() ,e); }

 添加依賴jar:

<dependency>
     <groupId>commons-httpclient</groupId>
     <artifactId>commons-httpclient</artifactId>
     <version>3.1</version>
</dependency>

 

end.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM