本文主要是介绍HttpPost--发送post请求到服务器并获取服务器返回值,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、 导入maven依赖
<dependency><groupId>commons-codec</groupId><artifactId>commons-codec</artifactId><version>1.9</version></dependency><dependency><groupId>commons-httpclient</groupId><artifactId>commons-httpclient</artifactId><version>3.1</version></dependency>
二、 工具类
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;/*** 发送请求到服务器并获取服务器返回值*/
class HttpPost {private static Logger LOGGER = LogManager.getLogger(HttpPost.class);/*** @param requestParam 请求参数* @param url 请求url* @return 服务器返回结果*/static String send(String url, String requestParam) throws Exception{//发送并获取服务器返回值String resultMsg = post(url ,requestParam);resultMsg = new String(resultMsg.getBytes(), "UTF-8");return resultMsg;}private static String post(String url,String requestParamStr) throws Exception {try {PostMethod method = new PostMethod(url);method.addRequestHeader("Accept", "application/json");method.addRequestHeader("Content-Type", "application/json");RequestEntity req = new StringRequestEntity(requestParamStr ,"application/json" ,"UTF-8");method.setRequestEntity(req);int statusCode = new HttpClient().executeMethod(method);LOGGER.debug("statusCode:" + statusCode);if (statusCode != HttpStatus.SC_OK) {LOGGER.error("method faild," + method.getStatusLine());}String response = new String(method.getResponseBody());LOGGER.debug("post response:" + response);return response;} catch (Exception e) {LOGGER.error("post failed", e);throw new Exception("post failed", e);}}
}
这篇关于HttpPost--发送post请求到服务器并获取服务器返回值的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!