您的位置 首页 java

Java httpClient 请求方式post 与get

/**
 * http 请求
 * @param message
 * @param url
 * @return
 */ public String RquestHttpMessage(String  message , String url) {
 // 创建 HttpClient  对象
  close able httpclient  httpClient= HttpClients.createDefault();
 CloseableHttpResponse response=null;
 String resultString = "";
 try{
 HttpPost httpPost=new HttpPost(url);
 StringEntity entity=new StringEntity(message,  ContentType .APPLICATION_JSON);
 //构建超时等配置信息
 RequestConfig  config  = RequestConfig.custom().setConnectTimeout(1000) //连接超时时间
 .setConnectionRequestTimeout(1000) //从连接池中取的连接的最长时间
 .setSocketTimeout(10 *1000) //数据传输的超时时间
 . build ();
// RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
 //设置请求配置时间
 httpPost.setConfig(config);
 httpPost.setEntity(entity);
 response=httpClient.execute(httpPost);
 if (response.getStatusLine().getStatusCode() == 200) {
 resultString= EntityUtils. toString (response.getEntity(),"utf-8");
 }
 }catch (IOException e){
 logger.info("请求失败");
 }finally {
 try{
 response.close();
 }catch (IOException e){
 logger.info("关闭连接失败");
 }
 }
 return "success";

 }

 /**
 * get 请求
 * @param url
 * @param param
 * @return
 */ public static String doGet(String url,  Map <String, String> param) {

 // 创建Httpclient对象
 CloseableHttpClient httpclient = HttpClients.createDefault();

 String resultString = "";
 CloseableHttpResponse response = null;
 try {
 // 创建uri
 URIBuilder builder = new URIBuilder(url);
 if (param != null) {
 for (String key : param.keySet()) {
 builder.addParameter(key, param.get(key));
 }
 }
 URI uri = builder.build();
 // 创建http GET请求
 HttpGet httpGet = new HttpGet(uri);
 // 执行请求
 response = httpclient.execute(httpGet);
 // 判断返回状态是否为200
 if (response.getStatusLine().getStatusCode() == 200) {
 resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
 }
 } catch (Exception e) {
 e.printStackTrace();
 } finally {
 try {
 if (response != null) {
 response.close();
 }
 httpclient.close();
 } catch (IOException e) {
 e.printStackTrace();
 }
 }
 return resultString;
 }

大家还有什么更好的方式,或者代码,工具类,可以说一下。

 

文章来源:智云一二三科技

文章标题:Java httpClient 请求方式post 与get

文章地址:https://www.zhihuclub.com/189900.shtml

关于作者: 智云科技

热门文章

网站地图