JAVA 调用HTTP接口POST或GET实现方式

        HTTP是一个客户端和服务器端请求和应答的标准(TCP),客户端是终端用户,服务器端是网站。通过使用Web浏览器、网络爬虫或者其它的工具,客户端发起一个到服务器上指定端口(默认端口为80)的HTTP请求。

具体POST或GET实现代码如下:

1package com.yoodb.util; 2 3import java.io.ByteArrayOutputStream; 4import java.io.IOException; 5import java.io.InputStream; 6 7import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler; 8import org.apache.commons.httpclient.HttpClient; 9import org.apache.commons.httpclient.HttpException; 10import org.apache.commons.httpclient.methods.GetMethod; 11import org.apache.commons.httpclient.methods.PostMethod; 12import org.apache.commons.httpclient.params.HttpMethodParams; 13 14public class HttpConnectUtil { 15 16 private static String DUOSHUO_SHORTNAME = "yoodb";//多说短域名 ****.yoodb.**** 17 private static String DUOSHUO_SECRET = "xxxxxxxxxxxxxxxxx";//多说秘钥 18 19 /** 20  * get方式 21  * @param url 22  * @author www.yoodb.com 23  * @return 24  */ 25 public static String getHttp(String url) { 26 String responseMsg = ""; 27 HttpClient httpClient = new HttpClient(); 28 GetMethod getMethod = new GetMethod(url); 29 getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler()); 30 try { 31 httpClient.executeMethod(getMethod); 32 ByteArrayOutputStream out = new ByteArrayOutputStream(); 33 InputStream in = getMethod.getResponseBodyAsStream(); 34 int len = 0; 35 byte[] buf = new byte[1024]; 36 while((len=in.read(buf))!=-1){ 37 out.write(buf, 0, len); 38 } 39 responseMsg = out.toString("UTF-8"); 40 } catch (HttpException e) { 41 e.printStackTrace(); 42 } catch (IOException e) { 43 e.printStackTrace(); 44 } finally { 45 //释放连接 46 getMethod.releaseConnection(); 47 } 48 return responseMsg; 49 } 50 51 /** 52  * post方式 53  * @param url 54  * @param code 55  * @param type 56  * @author www.yoodb.com 57  * @return 58  */ 59 public static String postHttp(String url,String code,String type) { 60 String responseMsg = ""; 61 HttpClient httpClient = new HttpClient(); 62 httpClient.getParams().setContentCharset("GBK"); 63 PostMethod postMethod = new PostMethod(url); 64 postMethod.addParameter(type, code); 65 postMethod.addParameter("client_id", DUOSHUO_SHORTNAME); 66 postMethod.addParameter("client_secret", DUOSHUO_SECRET); 67 try { 68 httpClient.executeMethod(postMethod); 69 ByteArrayOutputStream out = new ByteArrayOutputStream(); 70 InputStream in = postMethod.getResponseBodyAsStream(); 71 int len = 0; 72 byte[] buf = new byte[1024]; 73 while((len=in.read(buf))!=-1){ 74 out.write(buf, 0, len); 75 } 76 responseMsg = out.toString("UTF-8"); 77 } catch (HttpException e) { 78 e.printStackTrace(); 79 } catch (IOException e) { 80 e.printStackTrace(); 81 } finally { 82 postMethod.releaseConnection(); 83 } 84 return responseMsg; 85 } 86}

1、下面说一下多说单点登录(SSO)获取access_token访问多说API的凭证。

多说单点登录(SSO),授权结束后跳转回在sso中设置的login地址,注意这时候的URL带上了code参数,通过code获取access_token访问多说API的凭证,具体实现代码如下:

1public Map<String, String> getUserToken(String code){ 2 String url = "http://api.duoshuo.com/oauth2/access_token"; 3 String response = HttpConnectUtil.postHttp(url, code, "code"); 4 System.out.println(response); 5 Gson gson = new Gson(); 6 Map<String, String> retMap = gson.fromJson(response,new TypeToken<Map<String, String>>() {}.getType());  7 return retMap; 8}

返回参数是一个JSON串,包含user_id和access_token,user_id是该用户在多说的ID,access_token是访问多说API的凭证,处理成Map集合方便使用。

2、如果获取多说的用户信息,根据上一步获得的多说用户user_id来获取用户的具体信息,详情代码如下:

1public Map getProfiletMap(String userId){ 2 String url = "http://api.duoshuo.com/users/profile.json?user_id="+userId; 3 String response = HttpConnectUtil.getHttp(url); 4 response = response.replaceAll("\\\\", ""); 5 System.out.println(response); 6 Gson gson = new Gson(); 7 Map profile = gson.fromJson(response, Map.class); 8 return profile; 9}

上述使用了Google处理json数据的jar,如果对Gson处理json数据的方式不很了解,参考地址:http://www.yoodb.com/article/display/1033

返回的数据格式如下:

1{ 2    "response": { 3        "user_id": "13504206", 4        "name": "伤了心", 5        "url": "http://t.qq.com/wdg1115024292", 6        "avatar_url": "http://q.qlogo.cn/qqapp/100229475/F007A1729D7BCC84C106D6E4F2ECC936/100", 7        "threads": 0, 8        "comments": 0, 9        "social_uid": { 10            "qq": "F007A1729D7BCC84C106D6E4F2ECC936" 11        }, 12        "post_votes": "0", 13        "connected_services": { 14            "qqt": { 15                "name": "伤了心", 16                "email": null, 17                "avatar_url": "http://app.qlogo.cn/mbloghead/8a59ee1565781d099f3a/50", 18                "url": "http://t.qq.com/wdg1115024292", 19                "description": "没劲", 20                "service_name": "qqt" 21            }, 22            "qzone": { 23                "name": "?郁闷小佈?", 24                "avatar_url": "http://q.qlogo.cn/qqapp/100229475/F007A1729D7BCC84C106D6E4F2ECC936/100", 25                "service_name": "qzone" 26            } 27        } 28    }, 29    "code": 0 30}

获取的用户信息不方便查看,建议格式化一下,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

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

一篇文章带你了解JavaScript日期

日期对象允许您使用日期(年、月、日、小时、分钟、秒和毫秒)。一、JavaScript的日期格式一个JavaScript日期可以写为一个字符串:ThuFeb02201909:59:51GMT0800(中国标准时间)或者是一个数字:1486000791164写数字的日期,指定的毫秒数自1970年1月1日00:00:00到现在。1\.显示日期使用

HTTP与HTTPS介绍(非原创)

文章大纲一、HTTP和HTTPS的基本概念二、HTTP缺点三、HTTPS介绍四、免费HTTPS证书推荐一、HTTP和HTTPS的基本概念1.HTTP:是互联网上应用最为广泛的一种网络协议,是一个客户端和服务器端请求和应答的标准(TCP),用于从WWW服务器传输超文本到本地浏览器的

JAVA 调用HTTP接口POST或GET实现方式 - HelloWorld