java发起post请求—— body有参/无参

摘要:
importorg.apache.http.HttpEntity;importorg.apache.http.HttpStatus;importorg.apache.http.client.config.RequestConfig;importorg.apache.http.client.methods.CloseableHttpResponse;importorg.apache.http.cli
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
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;
1
/** 2 * 发起post请求 有参数的情况 3 * @paramurl 4 * @paramparams 5 * @paramcodePage 6 * @return 7 * @throwsException 8 */ 9 private synchronized static String postData(String url, Map<String, Object> params, String codePage) throwsException { 10 //创建post请求对象 11 HttpPost httppost = newHttpPost(url); 12 //获取到httpclient客户端 13 CloseableHttpClient httpclient =HttpClients.createDefault(); 14 try{ 15 //创建参数集合 16 List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>(); 17 //添加请求头参数 18 if(url.equals(GetOlapDataUrl)) { 19 httppost.addHeader("Content-Type", "application/json"); 20 httppost.addHeader("accessToken",params.get("accessToken").toString()); 21 } 22 //设置请求的一些配置设置,主要设置请求超时,连接超时等参数 23 RequestConfig requestConfig =RequestConfig.custom() 24 .setConnectTimeout(10000).setConnectionRequestTimeout(10000).setSocketTimeout(10000) 25 .build(); 26 httppost.setConfig(requestConfig); 27 //添加参数 28 httppost.setEntity(new StringEntity(JSONObject.toJSONString(params), ContentType.create("application/json", "utf-8"))); 29 //请求结果 30 String resultString = ""; 31 //启动执行请求,并获得返回值 32 CloseableHttpResponse response =httpclient.execute(httppost); 33 if (response.getStatusLine().getStatusCode() ==HttpStatus.SC_OK) { 34 //获取请求响应结果 35 HttpEntity entity =response.getEntity(); 36 if (entity != null) { 37 //将响应内容转换为指定编码的字符串 38 resultString = EntityUtils.toString(entity, "UTF-8"); 39 System.out.printf("Response content:{}", resultString); 40 returnresultString; 41 } 42 } else{ 43 System.out.println("请求失败!"); 44 returnresultString; 45 } 46 } catch(Exception e) { 47 throwe; 48 } finally{ 49 httpclient.close(); 50 } 51 return null; 52 } 53 54 /** 55 * 发起post请求 没有任何参数的情况 56 * 57 * @paramurl 请求的目标url地址 58 * @paramotherParam 其他参数 59 * @paramdata 请求数据 60 * @return将响应结果转换成string返回 61 * @throwsIOException 可能出现的异常 62 */ 63 private static String postMsg(String url, String otherParam) throwsIOException { 64 //根据url地址发起post请求 65 HttpPost httppost = newHttpPost(url); 66 //获取到httpclient客户端 67 CloseableHttpClient httpclient =HttpClients.createDefault(); 68 try{ 69 //设置请求的一些头部信息 70 httppost.addHeader("Content-Type", "application/json"); 71 httppost.addHeader("accessToken", otherParam); 72 //设置请求的一些配置设置,主要设置请求超时,连接超时等参数 73 RequestConfig requestConfig =RequestConfig.custom() 74 .setConnectTimeout(10000).setConnectionRequestTimeout(10000).setSocketTimeout(10000) 75 .build(); 76 httppost.setConfig(requestConfig); 77 //执行请求 78 CloseableHttpResponse response =httpclient.execute(httppost); 79 //请求结果 80 String resultString = ""; 81 if (response.getStatusLine().getStatusCode() ==HttpStatus.SC_OK) { 82 //获取请求响应结果 83 HttpEntity entity =response.getEntity(); 84 if (entity != null) { 85 //将响应内容转换为指定编码的字符串 86 resultString = EntityUtils.toString(entity, "UTF-8"); 87 System.out.printf("Response content:{}", resultString); 88 returnresultString; 89 } 90 } else{ 91 System.out.println("请求失败!"); 92 returnresultString; 93 } 94 } catch(Exception e) { 95 throwe; 96 } finally{ 97 httpclient.close(); 98 } 99 return null; 100 }

/** * 发起post请求 有参数的情况 * @param url * @param params * @param codePage * @return * @throws Exception */ private synchronized static String postData(String url, Map<String, Object> params, String codePage) throws Exception { //创建post请求对象 HttpPost httppost = new HttpPost(url); // 获取到httpclient客户端 CloseableHttpClient httpclient = HttpClients.createDefault(); try { //创建参数集合 List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>(); //添加请求头参数 if(url.equals(GetOlapDataUrl)) { httppost.addHeader("Content-Type", "application/json"); httppost.addHeader("accessToken",params.get("accessToken").toString()); } // 设置请求的一些配置设置,主要设置请求超时,连接超时等参数 RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(10000).setConnectionRequestTimeout(10000).setSocketTimeout(10000) .build(); httppost.setConfig(requestConfig); //添加参数 httppost.setEntity(new StringEntity(JSONObject.toJSONString(params), ContentType.create("application/json", "utf-8"))); // 请求结果 String resultString = ""; //启动执行请求,并获得返回值 CloseableHttpResponse response = httpclient.execute(httppost); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // 获取请求响应结果 HttpEntity entity = response.getEntity(); if (entity != null) { // 将响应内容转换为指定编码的字符串 resultString = EntityUtils.toString(entity, "UTF-8"); System.out.printf("Response content:{}", resultString); return resultString; } } else { System.out.println("请求失败!"); return resultString; } } catch (Exception e) { throw e; } finally { httpclient.close(); } return null; }/** * 发起post请求 没有任何参数的情况 * * @param url 请求的目标url地址 * @param otherParam 其他参数 * @param data 请求数据 * @return 将响应结果转换成string返回 * @throws IOException 可能出现的异常 */ private static String postMsg(String url, String otherParam) throws IOException { // 根据url地址发起post请求 HttpPost httppost = new HttpPost(url); // 获取到httpclient客户端 CloseableHttpClient httpclient = HttpClients.createDefault(); try { // 设置请求的一些头部信息 httppost.addHeader("Content-Type", "application/json"); httppost.addHeader("accessToken", otherParam); // 设置请求的一些配置设置,主要设置请求超时,连接超时等参数 RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(10000).setConnectionRequestTimeout(10000).setSocketTimeout(10000) .build(); httppost.setConfig(requestConfig); // 执行请求 CloseableHttpResponse response = httpclient.execute(httppost); // 请求结果 String resultString = ""; if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // 获取请求响应结果 HttpEntity entity = response.getEntity(); if (entity != null) { // 将响应内容转换为指定编码的字符串 resultString = EntityUtils.toString(entity, "UTF-8"); System.out.printf("Response content:{}", resultString); return resultString; } } else { System.out.println("请求失败!"); return resultString; } } catch (Exception e) { throw e; } finally { httpclient.close(); } return null; }

免责声明:文章转载自《java发起post请求—— body有参/无参》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Sentry 后端监控用Hashcat每秒计算1.4亿个密码,破解隔壁WIFI密码下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

WPF 创建桌面快捷方式

#region 创建桌面快捷方式 string deskTop = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop); string dirPath = System.Environment.CurrentDirectory;...

Java任意JSON字符串中,包含指定关键词的VALUE

1 /**Java任意JSON字符串中,包含指定关键词的json值*/ 2 public static voidmain(String[] s){ 3 String attrjson = "{"12":"100kg","96":"sd"}"; 4 JSONObject obj =(JSONObject) J...

java把一段时间分成周,月,季度,年的时间段

package com.mq.test.activeMQ; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date;...

Solr与MySQL查询性能对比

测试环境 本文简单对比下Solr与MySQL的查询性能速度。 测试数据量:10407608     Num Docs: 10407608 普通查询 这里对MySQL的查询时间都包含了从MySQL Server获取数据的时间。 在项目中一个最常用的查询,查询某段时间内的数据,SQL查询获取数据,30s左右 SELECT * FROM `tf_hotspotd...

hiveql函数笔记(二)

1、数据查询 //提高聚合的性能 SET hive.map.aggr=true; SELECT count(*),avg(salary) FROM employees; //木匾不允许在一个查询语句中使用多于一个的函数(DISTINCT。。。)表达式 SELECT count(DISTINCT symbol) FROM stocks; 表生成函数: exp...

C# 绘制统计图(柱状图, 折线图, 扇形图)

统计图形种类繁多, 有柱状图, 折线图, 扇形图等等, 而统计图形的绘制方法也有很多, 有Flash制作的统计图形, 有水晶报表生成统计图形, 有专门制图软件制作, 也有编程语言自己制作的;这里我们用就C# 制作三款最经典的统计图: 柱状图, 折线图和扇形图;既然是统计, 当然需要数据, 这里演示的数据存于Sql Server2000中, 三款统计图形都是...