您的位置:首页 > 编程语言 > Java开发

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

2015-09-14 22:48 831 查看
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://www.yoodb.com/article/display/1034
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: