HttpClient 远程接口调用方式
- <dependency>
- <groupId>org.apache.httpcomponents</groupId>
- <artifactId>httpclient</artifactId>
- </dependency>
- public static void doGet(){
- // 创建Httpclient对象
- CloseableHttpClient httpclient = HttpClients.createDefault();
- // 创建http GET请求
- HttpGet httpGet = new HttpGet("http://www.oschina.net/");
- CloseableHttpResponse response = null;
- try {
- // 执行请求
- response = httpclient.execute(httpGet);
- System.out.println(response.getStatusLine());
- // 判断返回状态是否为200
- if (response.getStatusLine().getStatusCode() == 200) {
- String content = EntityUtils.toString(response.getEntity(), "UTF-8");
- System.out.println("内容长度:" + content.length());
- }
- }catch(Exception e){
- e.printStackTrace();
- } finally {
- if (response != null) {
- try {
- response.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- try {
- httpclient.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- public static void doGetParam(){
- // 创建Httpclient对象
- CloseableHttpClient httpclient = HttpClients.createDefault();
- CloseableHttpResponse response = null;
- try {
- // 定义请求的参数
- URI uri = new URIBuilder("http://www.baidu.com/s").setParameter("wd", "数据库").build();
- System.out.println(uri);
- // 创建http GET请求
- HttpGet httpGet = new HttpGet(uri);
- // 执行请求
- response = httpclient.execute(httpGet);
- // 判断返回状态是否为200
- if (response.getStatusLine().getStatusCode() == 200) {
- String content = EntityUtils.toString(response.getEntity(), "UTF-8");
- System.out.println(content);
- }
- }catch(Exception e){
- e.printStackTrace();
- }finally {
- if (response != null) {
- try {
- response.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- try {
- httpclient.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- public static void doPost(){
- // 创建Httpclient对象
- CloseableHttpClient httpclient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();
- // 创建http POST请求
- HttpPost httpPost = new HttpPost("http://www.oschina.net/");
- CloseableHttpResponse response = null;
- try {
- // 执行请求
- response = httpclient.execute(httpPost);
- System.out.println(response.getStatusLine());
- // 判断返回状态是否为200
- if (response.getStatusLine().getStatusCode() == 200) {
- String content = EntityUtils.toString(response.getEntity(), "UTF-8");
- System.out.println(content);
- }
- }catch(Exception e){
- e.printStackTrace();
- }finally {
- if (response != null) {
- try {
- response.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- try {
- httpclient.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- public static void doPostParam() throws Exception{
- // 创建Httpclient对象
- CloseableHttpClient httpclient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();
- // 创建http POST请求
- HttpPost httpPost = new HttpPost("http://www.oschina.net/search");
- // 设置2个post参数,一个是scope、一个是q
- List<NameValuePair> parameters = new ArrayList<NameValuePair>();
- parameters.add(new BasicNameValuePair("scope", "project"));
- parameters.add(new BasicNameValuePair("q", "java"));
- // 构造一个form表单式的实体
- UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
- // 将请求实体设置到httpPost对象中
- httpPost.setEntity(formEntity);
- CloseableHttpResponse response = null;
- try {
- // 执行请求
- response = httpclient.execute(httpPost);
- System.out.println(response.getStatusLine());
- // 判断返回状态是否为200
- if (response.getStatusLine().getStatusCode() == 200) {
- String content = EntityUtils.toString(response.getEntity(), "UTF-8");
- System.out.println(content);
- }
- } finally {
- if (response != null) {
- response.close();
- }
- httpclient.close();
- }
- }
- obj.addHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
- obj.addHeader("User-Agent"," Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537. 36 (KHTML, like Gecko) Chrome/31.0.1650.63")
- package org.chu.ego.base.utils;
- import java.io.IOException;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Map;
- import org.apache.http.HttpEntity;
- import org.apache.http.NameValuePair;
- import org.apache.http.client.entity.UrlEncodedFormEntity;
- import org.apache.http.client.methods.CloseableHttpResponse;
- import org.apache.http.client.methods.HttpGet;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.client.utils.URIBuilder;
- import org.apache.http.impl.client.CloseableHttpClient;
- import org.apache.http.impl.client.HttpClientBuilder;
- import org.apache.http.impl.client.HttpClients;
- import org.apache.http.impl.client.LaxRedirectStrategy;
- import org.apache.http.message.BasicNameValuePair;
- import org.apache.http.util.EntityUtils;
- /**
- * --发送get请求的api
- * CloseableHttpClient类 ,client实现类
- * HttpClients类 ,client工具类,用于创建客户端对象。
- * CloseableHttpResponse接口,请求的响应对象
- * URIBuilder类 :url构建类,用于设置get请求的路径变量
- * HttpGet类 :get请求的发送对象
- * EntityUtils类 实体处理类
- *
- * --发送post 请求使用的api
- * CloseableHttpClient类
- * HttpClientBuilder client构建对象,用于创建客户端对象。
- * LaxRedirectStrategy类,post请求重定向的策略
- * CloseableHttpResponse 请求的响应对象
- * HttpPost post请求的发送对象
- * NameValuePair 类,用于设置参数值
- * UrlEncodedFormEntity:用于设置表单参数给发送对象HttpPost
- *
- * @author ranger
- *
- */
- public class HttpClientUtils {
- public static String doGet(String url,Map<String, String> params){
- //获取httpclient客户端
- CloseableHttpClient httpclient = HttpClients.createDefault();
- String resultString = "";
- CloseableHttpResponse response = null;
- try {
- URIBuilder builder = new URIBuilder(url);
- if(null!=params){
- for (String key:params.keySet()) {
- builder.setParameter(key, params.get(key));
- }
- }
- HttpGet get = new HttpGet(builder.build());
- response = httpclient.execute(get);
- System.out.println(response.getStatusLine());
- if(200==response.getStatusLine().getStatusCode()){
- HttpEntity entity = response.getEntity();
- resultString = EntityUtils.toString(entity, "utf-8");
- }
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- if(null!=response){
- try {
- response.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- if(null!=httpclient){
- try {
- httpclient.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- return resultString;
- }
- public static String doGet(String url){
- return doGet(url, null);
- }
- public static String doPost(String url,Map<String,String> params){
- /**
- * 在4.0及以上httpclient版本中,post需要指定重定向的策略,如果不指定则按默认的重定向策略。
- *
- * 获取httpclient客户端
- */
- CloseableHttpClient httpclient = HttpClientBuilder.create().setRedirectStrategy( new LaxRedirectStrategy()).build();
- String resultString = "";
- CloseableHttpResponse response = null;
- try {
- HttpPost post = new HttpPost(url);
- List<NameValuePair> paramaters = new ArrayList<>();
- if(null!=params){
- for (String key : params.keySet()) {
- paramaters.add(new BasicNameValuePair(key,params.get(key)));
- }
- UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity (paramaters);
- post.setEntity(formEntity);
- }
- /**
- * HTTP/1.1 403 Forbidden
- * 原因:
- * 有些网站,设置了反爬虫机制
- * 解决的办法:
- * 设置请求头,伪装浏览器
- */
- post.addHeader("user-agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
- response = httpclient.execute(post);
- System.out.println(response.getStatusLine());
- if(200==response.getStatusLine().getStatusCode()){
- HttpEntity entity = response.getEntity();
- resultString = EntityUtils.toString(entity, "utf-8");
- }
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- if(null!=response){
- try {
- response.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- if(null!=httpclient){
- try {
- httpclient.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- return resultString;
- }
- public static String doPost(String url){
- return doPost(url, null);
- }
- }
HttpClient 远程接口调用方式的更多相关文章
- HttpClient远程接口调用-实名认证
1.HttpClient远程接口调用 1)用户注册 注册按钮button提交表单时,要return false form表单 <!-- action="http://localhost ...
- libcurl 接口调用方式
http://hi.baidu.com/tracyu1026/item/bb6d5def4292b10b570f1d48 libcurl提供了一组C语言API函数直接调用.首先需要提到的两个函数就是c ...
- SmartRoute之远程接口调用和负载
基于接口的调用远比基于基础消息交互来得更简单和便于维护,特别在业务展现上,接口作为业务表现更适合其便利性.为了让SmartRoute更适合业务应用集成,在新的一年开始SmartRoute集成了远程接口 ...
- 【RPC】远程接口调用实例 的几种方式比较
pring中,用JMS搞RPC时会用到: org.springframework.jms.remoting.JmsInvokerServiceExporter org.springframework. ...
- 带SSL证书的httpclient 远程接口工具类
package com.iups.wx.util; import java.io.IOException; import java.io.UnsupportedEncodingException; i ...
- RMI(远程接口调用)
1. RMI的原理: RMI系统结构,在客户端和服务器端都有几层结构. 方法调用从客户对象经占位程序(Stub).远程引用层(Remote Reference Layer)和传输层(Transport ...
- HttpClient两种调用方式
一.参数字符串 /** * HttpClient请求接口 * @return 成功:音频字节 失败:null */ public static byte[] requestBaiduAudio(Str ...
- HTTP接口调用方式
1.get方式,设置调用方式为get,参数直接在url中包含,直接调用获取返回值即可 2.post方式,content为application/x-www-form-urlencoded ,参数格式 ...
- SpringBoot远程接口调用-RestTemplate使用
在web服务中,调度远程url是常见的使用场景,最初多采用原生的HttpClient,现采用Spring整合的RestTemplate工具类进行.实操如下: 1. 配置 主要用以配置远程链接的相关参数 ...
随机推荐
- useMemo优化React Hooks程序性能(九)
useMemo主要用来解决使用React hooks产生的无用渲染的性能问题.使用function的形式来声明组件,失去了shouldCompnentUpdate(在组件更新之前)这个生命周期,也就是 ...
- Apache-dbutils 简介及事务处理
一:commons-dbutils简介 commons-dbutils 是 Apache 组织提供的一个开源 JDBC工具类库,它是对JDBC的简单封装,学习成本极低,并且使用dbutils能极大简化 ...
- Tosca case status PLANNED,IN-WORK,COMPLETED 对应的图标
#PLANNED #IN-WORK #COMPLETED
- 005 DOM02
在上一篇DOM的基础上,继续案例的实践. 一:案例 1.禁用文本框 <!DOCTYPE html> <html lang="en"> <head> ...
- leetcode 290. Word Pattern 、lintcode 829. Word Pattern II
290. Word Pattern istringstream 是将字符串变成字符串迭代器一样,将字符串流在依次拿出,比较好的是,它不会将空格作为流,这样就实现了字符串的空格切割. C++引入了ost ...
- Linux 在 TOP 命令中切换内存的显示单位
顶部的内存信息可以在top运行时按E切换,每次切换转换率为1000,只是没有单位,切换的单位为 k,m,g,t,p: 1. 2. 3., 4. 底下的进程信息按e切换,每次切换转换率为1000,切换的 ...
- log4j 异常时在日志文件里面显示空的。
如下图所示,输入的时候不要写 e.getStackTrace() 一般情况下不会出问题,但有时候就会出问题 解决方案
- 定时备份删除数据库sql
1.备份数据库 mkdir -p /home/mysql/mysql_bak/ vi mysql_bak.sh #!/bin/bash #Shell Command For Backup MySQL ...
- C#DbHelperOleDb,Access数据库帮助类 (转)
/// <summary>/// 编 码 人:苏飞/// 联系方式:361983679 /// 更新网站:[url=http://www.sufeinet.com/thread-655- ...
- LeetCode_303. Range Sum Query - Immutable
303. Range Sum Query - Immutable Easy Given an integer array nums, find the sum of the elements betw ...