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

Wesley13
• 阅读 1129

        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

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
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
Karen110 Karen110
2年前
一篇文章带你了解JavaScript日期
日期对象允许您使用日期(年、月、日、小时、分钟、秒和毫秒)。一、JavaScript的日期格式一个JavaScript日期可以写为一个字符串:ThuFeb02201909:59:51GMT0800(中国标准时间)或者是一个数字:1486000791164写数字的日期,指定的毫秒数自1970年1月1日00:00:00到现在。1\.显示日期使用
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Wesley13 Wesley13
2年前
HTTP与HTTPS介绍(非原创)
文章大纲一、HTTP和HTTPS的基本概念二、HTTP缺点三、HTTPS介绍四、免费HTTPS证书推荐一、HTTP和HTTPS的基本概念1.HTTP:是互联网上应用最为广泛的一种网络协议,是一个客户端和服务器端请求和应答的标准(TCP),用于从WWW服务器传输超文本到本地浏览器的
Stella981 Stella981
2年前
Linux模拟HTTP请求
一个简单的GET请求使用curl命令可以轻松发起一个HTTP请求:使用GET凡是请求网址curlhttp://www.baidu.com可以使用X选项指定请求方式携带参数的POST请求下面演示一个带头部和参数的POST请求curlXPOST\'http://u
Stella981 Stella981
2年前
Android So动态加载 优雅实现与原理分析
背景:漫品Android客户端集成适配转换功能(基于目标识别(So库35M)和人脸识别库(5M)),导致apk体积50M左右,为优化客户端体验,决定实现So文件动态加载.!(https://oscimg.oschina.net/oscnet/00d1ff90e4b34869664fef59e3ec3fdd20b.png)点击上方“蓝字”关注我
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Docker 部署SpringBoot项目不香吗?
  公众号改版后文章乱序推荐,希望你可以点击上方“Java进阶架构师”,点击右上角,将我们设为★“星标”!这样才不会错过每日进阶架构文章呀。  !(http://dingyue.ws.126.net/2020/0920/b00fbfc7j00qgy5xy002kd200qo00hsg00it00cj.jpg)  2
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Json格式Java封装天猫商品详情数据接口,实现海量商品采集业务
根据天猫的API文档,获取天猫商品详情的API是通过发送Http/Post/GET请求,其中itemID是具体的商品ID。以下是Python和Java封装获取天猫商品详情API(复制Taobaoapi2014)的示例代码:1.请求方式:HTTPPOSTGE