HttpClient--使用HttpClient进行Get Post请求访问
在java后台开发中,我们有时候需要调用其他网站的接口进行数据的获取操作,我们一般会采用
1.java net 包中的URL 类,进行网络的数据获取
2.使用apache提供的HttpClient进行网络中数据的获取;
这里我们使用第二种方式,使用apache 提供的HttpClient进行数据的获取,接口的对接,下面附上HttpClientUtil 工具类,实现了POST与GET方法
1.引入pom依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.3.1</version>
</dependency>
package com.project.utils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
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; public class HttpClientUtils { //使用HttpClient 进行doGET请求
public static String doGet(String url) throws Exception { CloseableHttpClient httpclient =HttpClients.createDefault();
HttpGet httpget =new HttpGet(url);
try {
HttpResponse response=httpclient.execute(httpget);
//创建响应处理器处理服务器响应内容
String content = Utf8ResponseHandler.INSTANCE.handleResponse(response); return content; } finally {
httpget.releaseConnection();
} } public static void main(String[] args) throws Exception { String str=doPOST("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN","nm");
System.out.println(str); } //使用HttpClient 进行dopOSTT请求,适合发送的数据为json数据格式
public static String doPOST(String url,String outstr) throws Exception { //DefaultHttpClient httpclient =new DefaultHttpClient();//老版本的方法
CloseableHttpClient httpclient =HttpClients.createDefault();
HttpPost httppost =new HttpPost(url);
String result =null;
try {
httppost.setEntity(new StringEntity(outstr, "UTF-8"));
HttpResponse response=httpclient.execute(httppost);
//创建响应处理器处理服务器响应内容
String content = Utf8ResponseHandler.INSTANCE.handleResponse(response); return content; }
finally { httppost.releaseConnection();
} }
//传递form 表单
public static String NameValue(String URL,Map<String,String> formArgs) throws Exception { HttpClient httpclient = HttpClients.createDefault(); HttpPost post =new HttpPost(URL); List<BasicNameValuePair> data =new ArrayList<BasicNameValuePair>(); for(Map.Entry<String, String> entry :formArgs.entrySet()) { data.add(new BasicNameValuePair(entry.getKey(), entry.getValue()) );
}
try {
post.setEntity(new UrlEncodedFormEntity(data)); HttpResponse response=httpclient.execute(post); String content = Utf8ResponseHandler.INSTANCE.handleResponse(response); return content;
}
finally { post.releaseConnection();
} } }
创建响应处理器--utf-8编码(需要继承ResponseHandler 实现自己的方法,官方也有自己默认的一套实现方法BasicResponseHandler,但不能设置编码)
package com.project.utils; import java.io.IOException; import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils; public class Utf8ResponseHandler implements ResponseHandler<String> { /*
*实现utf-8编码的返回数据类型,实现ttpclient ResponseHandler接口方法
*
*copy from {@link org.apache.http.impl.client.BasicResponseHandler}官方默认提供
*/
public static final ResponseHandler<String> INSTANCE = new Utf8ResponseHandler(); @Override
public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
final StatusLine statusLine = response.getStatusLine();
final HttpEntity entity = response.getEntity();
if (statusLine.getStatusCode() >= 300) {
EntityUtils.consume(entity);
throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
}
return entity == null ? null : EntityUtils.toString(entity, Consts.UTF_8);
} }
HttpClient--使用HttpClient进行Get Post请求访问的更多相关文章
- httpClient Post例子,Http 四种请求访问代码 HttpGet HttpPost HttpPut HttpDelete
httpclient post方法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 //----1. HttpPost request = new HttpPost(ur ...
- 使用HttpClient实现对第三方服务器的请求并接受返回数据
/* * 创建日期 2017-4-7 * * TODO 要更改此生成的文件的模板,请转至 * 窗口 - 首选项 - Java - 代码样式 - 代码模板 */ package com.enfo.int ...
- HttpClient 以post的方式发送请求(由于请求参数太多所以改成以post提交表单的方式)
1:Util类方法 /** * 发送 Post请求 * * @param url * @param reqXml * @return */ public static String post(Stri ...
- HttpClient之Get请求和Post请求示例
HttpClient之Get请求和Post请求示例 博客分类: Java综合 HttpClient的支持在HTTP/1.1规范中定义的所有的HTTP方法:GET, HEAD, POST, PUT, ...
- c#后台代码请求访问api接口
前言:最近公司项目与外部api接口对接较多 ,写下自己的代码总结.介绍两种访问方式(HttpClient.HttpWebRequest) 一.HttpWebRequest 访问Api private ...
- 新旧apache HttpClient 获取httpClient方法
在apache httpclient 4.3版本中对很多旧的类进行了deprecated标注,通常比较常用的就是下面两个类了. DefaultHttpClient -> CloseableHtt ...
- SharePoint\O365 CSOM操作"请求访问设置"功能
博客地址:http://blog.csdn.net/FoxDave 请求访问设置是在SharePoint网站权限菜单中的一个功能,如下图: 它用来设置成员是否可以共享网站以及个别文件和文件夹,是否允许 ...
- WebGIS空间数据请求访问机制
通用的WebGIS空间数据请求访问机制如下图所示: 图1 WebGIS空间数据请求访问机制
- 基于Ryu的服务器实现及相关请求访问处理
基于Ryu的服务器实现及相关请求访问处理 前言及问题描述 近期又遇到了一个非常棘手的问题,由于Ryu是通过Python语言开发的,通过Ryu的wsgi的方式建立服务器,无法解析PHP,通过多次方法解决 ...
- java使用线程请求访问每次间隔10分钟连续5次,之后停止请求
java使用线程请求访问每次间隔10分钟连续5次,收到相应的时候停止请求 package com.qlwb.business.util; /** * * * @类编号: * @类名称:RequestT ...
随机推荐
- redis 学习笔记3(哨兵模式下分布式锁的实现以及全局唯一id的生成)
redis实现分布式锁和全局唯一id应该是较为常见的应用. 实现基于redis的setNX,以及incr命令.还是比较简单的! 搭建环境以及配置好sping整合,做了下测试,有兴趣的载下来看看,自己做 ...
- 安装 nginx
一.安装准备 首先由于nginx的一些模块依赖一些lib库,所以在安装nginx之前,必须先安装这些lib库,这些依赖库主要有g++.gcc.openssl-devel.pcre-devel和zlib ...
- Servlet基本_初期化パラメータ、外部ファイル
1.サーブレットの初期化パラメータサーブレットの初期化パラメータを利用するには.必ずweb.xmlにおいてサーブレットマッピングを指定する必要がある.(Tomactのinvokerサーブレットは利用で ...
- 遍历DOM树,理解更新范围
在JavaScript中,如果需求对多个元素重复进行同样的操作,就需要写一个循环来遍历选中的所有元素. 在jQuery中,当选择器返回了多个元素时,可以使用一个方法来更新所有的元素,不再需要使用循环. ...
- c/c++基础 const
int main(int argc, char* argv[]) { '; '; a1='; //a2='2'; //a2是字符常量 "; "; a3="; //a4=& ...
- [原创]HTML 用div模拟select下拉框
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML xmlns=" ...
- eval 用法
计算 eval('1+1') # 2 在字典中提取键 的值 eval('a',{'a':1}) # 1 计算 Boolean 值 eval( 'True',{'a':1}) # True eval(' ...
- Ajax 学习 第三篇
1.什么是json 第一种方法 第二种方法 比较evar and jsondata 任何时候使用EVAR要特别小心,他不会管输入对象的类型 JSONLint可以在线校验代码的正确性 改写代码
- C++ MFC常用函数(转)
WinExec() ExitWindowsEx() GlobalMemoryStatus() GetSystemInfo() GetSystemDirectory() GetWindowsDirect ...
- Assetbundle创建与加载
[Assetbundle创建与加载] Unity有两种动态加载机制:一种是Resource.Load.一种是AssetBundle.Assetbundle是Unity Pro提供的功能,它可以把多个游 ...