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.