原创

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://blog.yoodb.com/yoodb/article/detail/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对象。

~阅读全文-人机检测~

微信公众号“Java精选”(w_z90110),专注Java技术干货分享!让你从此路人变大神!回复关键词领取资料:如Mysql、Hadoop、Dubbo、Spring Boot等,免费领取视频教程、资料文档和项目源码。微信搜索小程序“Java精选面试题”,内涵3000+道Java面试题!

涵盖:互联网那些事、算法与数据结构、SpringMVC、Spring boot、Spring Cloud、ElasticSearch、Linux、Mysql、Oracle等

评论

  1. #1

    斗地主 (2017/06/20 21:56:05)回复
    感谢分享,正在使用这个中,正好赶上啦。

    路人甲 (2017/09/21 17:43:19)回复
    这个我是我自己写过的工具,在其他博客上也有,没事分享给大家,仅供参考。

分享:

支付宝

微信