900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > HttpClient发送get/post请求

HttpClient发送get/post请求

时间:2020-02-08 18:44:11

相关推荐

HttpClient发送get/post请求

1.需要的maven依赖:

<!--httpClient需要的依赖--><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.2</version></dependency><!--//httpclient缓存--><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient-cache</artifactId><version>4.5</version></dependency><!--//http的mime类型都在这里面--><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpmime</artifactId><version>4.3.2</version></dependency>

2.发送get请求

//使用httpClient发送get请求public void sentGetMethod(){//1.先创建httpClient对象,使用默认的方式即可CloseableHttpClient httpClient= HttpClients.createDefault();//2.设置url并且创建某种请求方式实例//比如:(在百度上搜索helloworld出现的路径)url:/s?ie=utf-8&f=8&rsv_bp=0// &rsv_idx=1&tn=baidu&wd=helloworld&rsv_pq=c6735cf70000fe15// &rsv_t=7e25dm7uzHpmOwrFNF33FXbom45Px0Bs0F8PP3Bcm8RMOysmKlfA%2FuqKoU4&rqlang=cn// &rsv_enter=1&rsv_sug3=9&rsv_sug1=5&rsv_sug7=101//url的构建也可以使用字符串拼接的方式try {URI url=new URIBuilder().setScheme("https")//设置协议.setHost("").setPath("/s").setParameter("ie","utf-8").setParameter("rsv_idx","1").setParameter("tn","baidu").setParameter("wd","helloworld").setParameter("rsv_pq","c6735cf70000fe15").setParameter("rsv_t","7e25dm7uzHpmOwrFNF33FXbom45Px0Bs0F8PP3Bcm8RMOysmKlfA%2FuqKoU4").setParameter("rqlang","cn").setParameter("rsv_enter","1").setParameter("rsv_sug3","9").setParameter("rsv_sug1","5").setParameter("rsv_sug7","101").build();System.out.println(url);HttpGet httpGet=new HttpGet(url);InputStream inputStream=null;CloseableHttpResponse httpResponse=null;try {//3.执行httpClienthttpResponse=httpClient.execute(httpGet);//可以输出请求的结果System.out.println(httpResponse.getStatusLine().getStatusCode());//4.获取相应的结果//4.1使用EntityUtils.toString()方式 --不推荐//2种方式只能2选一存在,会互相冲突HttpEntity entity=httpResponse.getEntity(); //获取响应的实体//if (entity!=null){//System.out.println(EntityUtils.toString(entity,"utf-8"));//}else {////如果entity为空,那么直接消化掉即可//EntityUtils.consume(entity);//}System.out.println("------------------------我是美丽的分割线--------------------");//4.2使用InputStream方式 --推建inputStream=entity.getContent();//转换成字符流BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));String line="";while ((line=bufferedReader.readLine())!=null){System.out.println(line);}} catch (IOException e) {e.printStackTrace();}finally {//关闭InputStream和responseif (inputStream!=null){try {inputStream.close();} catch (IOException e) {e.printStackTrace();}}if (httpResponse!=null){try {httpResponse.close();} catch (IOException e) {e.printStackTrace();};}}} catch (URISyntaxException e) {e.printStackTrace();}}

3.httpClient发送post请求(携带json数据)

//发送post请求 携带json数据的public void sendPostMethod(String url){//1.创建httpClientCloseableHttpClient httpClient=HttpClients.createDefault();//2.创建post请求方式实例HttpPost httpPost=new HttpPost(url);//2.1设置请求头 发送的是json数据格式httpPost.setHeader("Content-type", "application/json;charset=utf-8");httpPost.setHeader("Connection", "Close");//3.设置参数---设置消息实体 也就是携带的数据/** 比如传递:* {"username": "aries","password": "666666"}*/String jsonStr=" {\"username\":\"aries\",\"password\":\"666666\"}";StringEntity entity = new StringEntity(jsonStr.toString(), Charset.forName("UTF-8"));entity.setContentEncoding("UTF-8"); //设置编码格式// 发送Json格式的数据请求entity.setContentType("application/json");//把请求消息实体塞进去httpPost.setEntity(entity);//4.执行http的post请求CloseableHttpResponse httpResponse=null;InputStream inputStream=null;try {httpResponse=httpClient.execute(httpPost);//5.对返回的数据进行处理//5.1判断是否成功System.out.println(httpResponse.getStatusLine().getStatusCode());//5.2对数据进行处理HttpEntity httpEntity=httpResponse.getEntity();inputStream=httpEntity.getContent(); //获取content实体内容//封装成字符流来输出BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));String line="";while ((line=bufferedReader.readLine())!=null){System.out.println(line);}} catch (IOException e) {e.printStackTrace();}finally {//6.关闭inputStream和httpResponseif (inputStream!=null){try {inputStream.close();} catch (IOException e) {e.printStackTrace();}}if (httpResponse!=null){try {httpResponse.close();} catch (IOException e) {e.printStackTrace();}}}}

4.httpClient发送post请求/携带x-www-form-urlencoded数据格式

//发送post请求 携带非json数据public void sendPostMethod1(String url) throws Exception {// 1、创建一个httpClient客户端对象CloseableHttpClient httpClient=HttpClients.createDefault();// 2、创建一个HttpPost请求HttpPost httpPost = new HttpPost(url);//设置请求头httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); //设置传输的数据格式//携带普通的参数params的方式List<NameValuePair> params=new ArrayList<>();params.add(new BasicNameValuePair("username", "kylin"));params.add(new BasicNameValuePair("password", "123456"));String str=EntityUtils.toString(new UrlEncodedFormEntity(params,Consts.UTF_8));//这里就是:username=kylin&password=123456System.out.println(str);//放参数进post请求里面 从名字可以知道 这个类是专门处理x-www-form-urlencoded 添加参数的httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));// 7、执行post请求操作,并拿到结果CloseableHttpResponse httpResponse = httpClient.execute(httpPost);// 获取结果实体HttpEntity entity = httpResponse.getEntity();if (entity != null) {//进行输出操作 这里就简单的使用EntityUtils工具类的toString()方法System.out.println(EntityUtils.toString(entity,"UTF-8"));}else EntityUtils.consume(entity);//最后释放资源之类的}

总结:

1.创建httpClient对象创建默认的对象就够使用了

2.创建某种请求方法的实例

例如有:get方式---- HttpGet

post方式-----HttpPost

put方式------HttpPut

delete方式 ------HttpDelete

3.如果有参数的话就设置参数

get请求:

方式1:使用URI类的方法来创建

方式2:直接使用字符串拼接那种

post请求:

使用setEntity()方式来携带不同的数据类型(需要设置)

4.发送请求

执行httpClient.execute() --返回CloseableHttpResponse对象

5.获取请求的结果

获取HttpEntity的实体之后,对http文档的查看

方式一:EntityUtils.toString(entity,"utf-8") 不推荐

方式二:使用InputStream类

6.关闭连接释放资源

先关闭inputStream

再关闭response

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。