http post请求
代码
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
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;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/**
*
* POST接口服务的JAVA示例
*
*/
public class HttpPostApiInvoker {
private final static String URL = "http://test/url"; // 请求url
private final static String REQUEST_CHARSET = "UTF-8";
private final static String RESPONSE_CHARSET = "UTF-8";
private final static int CONNECT_TIMEOUT = 5000; // 调用连接超时时间
private final static int REQUEST_TIMEOUT = 10000; // 调用获取数据超时时间
public static void main(String[] args) throws Exception{
HttpPostApiInvoker httpPostApiInvoker = new HttpPostApiInvoker();
List<NameValuePair> parameterList = httpPostApiInvoker.prepareParameter();
String result = httpPostApiInvoker.invoke(parameterList);
System.out.println(result);
}
/***
* 准备业务参数
* @return
*/
private List<NameValuePair> prepareParameter(){
List<NameValuePair> parameterList = new ArrayList<>();
parameterList.add(new BasicNameValuePair("name", "xxxx"));
parameterList.add(new BasicNameValuePair("password", "xxxxxxxxx"));
return parameterList;
}
/***
* 没有使用长连接
* @param parameterList
* @return JSON格式的字符串
* @throws IOException
*/
private String invoke(List<NameValuePair> parameterList) throws IOException {
HttpPost httpPost = null;
String result = "";
try {
httpPost = new HttpPost(URL);
//设置超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(CONNECT_TIMEOUT)
.setSocketTimeout(REQUEST_TIMEOUT)
.build();
httpPost.setConfig(requestConfig);
CloseableHttpClient httpClient = HttpClients.createDefault();
httpPost.setEntity(new UrlEncodedFormEntity(parameterList, REQUEST_CHARSET));
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
//返回值不是200,进行错误处理
if(HttpStatus.SC_OK != httpResponse.getStatusLine().getStatusCode()){
//相关处理
if(null != httpPost) {
httpPost.abort();
}
return result;
}
//获取结果
result = EntityUtils.toString(httpEntity, RESPONSE_CHARSET);
}catch(Exception e){
if(null != httpPost){
httpPost.abort();
}
throw e;
}
return result;
}
}
项目依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2 </version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version> 4.3.6</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4</version>
</dependency>