JAVA 调用HTTP接口POST或GET实现方式
HTTP是一个客户端和服务器端请求和应答的标准(TCP),客户端是终端用户,服务器端是网站。通过使用Web浏览器、网络爬虫或者其它的工具,客户端发起一个到服务器上指定端口(默认端口为80)的HTTP请求。
具体POST或GET实现代码如下:
package com.yoodb.util; import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream; import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams; public class HttpConnectUtil { private static String DUOSHUO_SHORTNAME = "yoodb";//多说短域名 ****.yoodb.****
private static String DUOSHUO_SECRET = "xxxxxxxxxxxxxxxxx";//多说秘钥 /**
* get方式
* @param url
* @author www.yoodb.com
* @return
*/
public static String getHttp(String url) {
String responseMsg = "";
HttpClient httpClient = new HttpClient();
GetMethod getMethod = new GetMethod(url);
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());
try {
httpClient.executeMethod(getMethod);
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream in = getMethod.getResponseBodyAsStream();
int len = 0;
byte[] buf = new byte[1024];
while((len=in.read(buf))!=-1){
out.write(buf, 0, len);
}
responseMsg = out.toString("UTF-8");
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//释放连接
getMethod.releaseConnection();
}
return responseMsg;
} /**
* post方式
* @param url
* @param code
* @param type
* @author www.yoodb.com
* @return
*/
public static String postHttp(String url,String code,String type) {
String responseMsg = "";
HttpClient httpClient = new HttpClient();
httpClient.getParams().setContentCharset("GBK");
PostMethod postMethod = new PostMethod(url);
postMethod.addParameter(type, code);
postMethod.addParameter("client_id", DUOSHUO_SHORTNAME);
postMethod.addParameter("client_secret", DUOSHUO_SECRET);
try {
httpClient.executeMethod(postMethod);
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream in = postMethod.getResponseBodyAsStream();
int len = 0;
byte[] buf = new byte[1024];
while((len=in.read(buf))!=-1){
out.write(buf, 0, len);
}
responseMsg = out.toString("UTF-8");
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
postMethod.releaseConnection();
}
return responseMsg;
}
}
1、下面说一下多说单点登录(SSO)获取access_token访问多说API的凭证。
多说单点登录(SSO),授权结束后跳转回在sso中设置的login地址,注意这时候的URL带上了code参数,通过code获取access_token访问多说API的凭证,具体实现代码如下:
public Map<String, String> getUserToken(String code){
String url = "http://api.duoshuo.com/oauth2/access_token";
String response = HttpConnectUtil.postHttp(url, code, "code");
System.out.println(response);
Gson gson = new Gson();
Map<String, String> retMap = gson.fromJson(response,new TypeToken<Map<String, String>>() {}.getType());
return retMap;
}
返回参数是一个JSON串,包含user_id和access_token,user_id是该用户在多说的ID,access_token是访问多说API的凭证,处理成Map集合方便使用。
2、如果获取多说的用户信息,根据上一步获得的多说用户user_id来获取用户的具体信息,详情代码如下:
public Map getProfiletMap(String userId){
String url = "http://api.duoshuo.com/users/profile.json?user_id="+userId;
String response = HttpConnectUtil.getHttp(url);
response = response.replaceAll("\\\\", "");
System.out.println(response);
Gson gson = new Gson();
Map profile = gson.fromJson(response, Map.class);
return profile;
}
上述使用了Google处理json数据的jar,如果对Gson处理json数据的方式不很了解,参考地址:http://www.yoodb.com/article/display/1033
返回的数据格式如下:
{
"response": {
"user_id": "13504206",
"name": "伤了心",
"url": "http://t.qq.com/wdg1115024292",
"avatar_url": "http://q.qlogo.cn/qqapp/100229475/F007A1729D7BCC84C106D6E4F2ECC936/100",
"threads": 0,
"comments": 0,
"social_uid": {
"qq": "F007A1729D7BCC84C106D6E4F2ECC936"
},
"post_votes": "0",
"connected_services": {
"qqt": {
"name": "伤了心",
"email": null,
"avatar_url": "http://app.qlogo.cn/mbloghead/8a59ee1565781d099f3a/50",
"url": "http://t.qq.com/wdg1115024292",
"description": "没劲",
"service_name": "qqt"
},
"qzone": {
"name": "?郁闷小佈?",
"avatar_url": "http://q.qlogo.cn/qqapp/100229475/F007A1729D7BCC84C106D6E4F2ECC936/100",
"service_name": "qzone"
}
}
},
"code": 0
}
获取的用户信息不方便查看,建议格式化一下,Json校验或格式化地址:http://www.yoodb.com/toJson,返回数据参数说明:
code int 一定返回
结果码。0为成功。失败时为错误码。
errorMessage strin
错误消息。当code不为0时,返回错误消息。
response object
json对象。当code为0时,返回请求到的json对象。
来源:http://blog.yoodb.com/yoodb/article/detail/1034
JAVA 调用HTTP接口POST或GET实现方式的更多相关文章
- Java调用webservice接口方法
java调用webservice接口 webservice的 发布一般都是使用WSDL(web service descriptive langu ...
- Java 调用http接口(基于OkHttp的Http工具类方法示例)
目录 Java 调用http接口(基于OkHttp的Http工具类方法示例) OkHttp3 MAVEN依赖 Http get操作示例 Http Post操作示例 Http 超时控制 工具类示例 Ja ...
- (二)通过JAVA调用SAP接口 (增加一二级参数)
(二)通过JAVA调用SAP接口 (增加一二级参数) 一.建立sap连接 请参考我的上一篇博客 JAVA连接SAP 二.测试项目环境准备 在上一篇操作下已经建好的环境后,在上面的基础上新增类即可 三. ...
- Java调用RestFul接口
使用Java调用RestFul接口,以POST请求为例,以下提供几种方法: 一.通过HttpURLConnection调用 1 public String postRequest(String url ...
- Android-WebView与本地HTML (Java调用--->HTML的方法)-(new WebView(this)方式)
之前的博客,Android-WebView与本地HTML (Java调用--->HTML的方法),是在 findViewById(R.id.webview);,来得到WebView, 此博客使用 ...
- Java调用第三方接口工具类(json、form)
1.JSON值访问 /** * 调用对方接口方法 * @param path 对方或第三方提供的路径 * @param data 向对方或第三方发送的数据,大多数情况下给对方发送JSON数据让对方解析 ...
- java 调用webservice接口wsdl,推荐使用wsdl2java,放弃wsimport
网上说wsimport是jdk1.6后自带的客户端生成调用webservice接口的工具,其实我挺喜欢原生的东西,毕竟自家的东西用着应该最顺手啊,但往往让人惊艳的是那些集成工具. 本机jdk1.8.1 ...
- Java调用第三方接口示范
在项目开发中经常会遇到调用第三方接口的情况,比如说调用第三方的天气预报接口. 使用流程[1]准备工作:在项目的工具包下导入HttpClientUtil这个工具类,或者也可以使用Spring框架的res ...
- 三种方法实现java调用Restful接口
1,基本介绍 Restful接口的调用,前端一般使用ajax调用,后端可以使用的方法比较多, 本次介绍三种: 1.HttpURLConnection实现 2.HttpClient实现 3.Spring ...
随机推荐
- java猜数游戏
java随机数的产生 int number=(int)(Math.random()*10+1) Math.random()*n //n个随机数,从0开始 do{}while循环 //猜数,1到10的随 ...
- 爬虫4:pdf页面+pdfminer模块+demo
本文介绍下pdf页面的爬取,需要借助pdfminer模块 demo一般流程: 1)设置url url = 'http://www.------' + '.PDF' 2)requests模块获取url ...
- SpringBoot系列:Spring Boot集成Spring Cache
一.关于Spring Cache 缓存在现在的应用中越来越重要, Spring从3.1开始定义了org.springframework.cache.Cache和org.springframework. ...
- Vue核心之数据劫持
前瞻 当前前端界空前繁荣,各种框架横空出世,包括各类mvvm框架横行霸道,比如Anglar,Regular,Vue,React等等,它们最大的优点就是可以实现数据绑定,再也不需要手动进行DOM操作了, ...
- [LUOGU2964] [USACO09NOV]硬币的游戏A Coin Game
题目描述 Farmer John's cows like to play coin games so FJ has invented with a new two-player coin game c ...
- 生产环境下,MySQL大事务操作导致的回滚解决方案
如果mysql中有正在执行的大事务DML语句,此时不能直接将该进程kill,否则会引发回滚,非常消耗数据库资源和性能,生产环境下会导致重大生产事故. 如果事务操作的语句非常之多,并且没有办法等待那么久 ...
- Logstash 入门
一.简介 Logstash 是开源的服务器端数据处理管道,支持从不同来源采集数据,装换数据,并将数据发送到不同的存储库中. Logstash 项目诞生于 2009 年 8 月 2 日.其作者是世界著名 ...
- Java描述设计模式(16):代理模式
本文源码:GitHub·点这里 || GitEE·点这里 一.生活场景 1.场景描述 在电商高速发展的今天,快递的数量十分庞大,甚至出现了快递代理行业,简单的说就是快递的主人没有时间收快递,会指定一个 ...
- 关于举办【福州】《K8S社区线下技术交流会》的问卷调查
近年来,容器.Kubernetes.DevOps.微服务.Serverless等一系列云原生技术受到越来越多的关注,云原生为企业数字化转型提供了创新源动力,基于云原生技术构建企业技术中台在各行业也 ...
- python-Debug、函数装饰器
Debug操作: 程序出问题的时候可以用debug来看一下代码运行轨迹,然后找找问题在哪里 1.先给即将debug的代码打上断点: 2.打完断点之后右键点击debug: 3.然后依次点击开始按钮让 ...