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://www.yoodb.com/article/display/1034

时间: 2024-08-06 10:09:06

JAVA 调用HTTP接口POST或GET实现方式的相关文章

Java调用https接口,避免证书的方式

一.使用httpClient调用 1.使用maven添加依赖 <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.3</version> </dependency> <dependency> <groupId>org.apach

java调用飞信接口免费短信发送到对方手机

原文:java调用飞信接口免费短信发送到对方手机 源代码下载地址:http://www.zuidaima.com/share/1550463460084736.htm 飞信发送信息限(移动用户) 1.用飞信加为好友才可以跟对方发飞信(达到此条件发飞信不收取费用) 2.FetionConfig配置文件里的 WeekendGreetings=是发送另一个配置文件名 如 WeekendGreetings=周末问候 就是 周末问候 文件里的内容 每一行 就是一条飞信 phone=你的手机号码 pwd=你

java调用webservice接口方法

webservice的 发布一般都是运用WSDL(web service descriptive language)文件的款式来发布的,在WSDL文件里边,包含这个webservice暴露在外面可供运用的接口.今日查找到了非常好的 webservice provider列表 http://www.webservicex.net/WCF/default.aspx 这上面列出了70多个包含许多方面的free webservice provider,utilities->global weather就

Java调用WebService 接口 实例

这里给大家介绍一下,Java调用webservice的一个实例的过程. 本项目不能运行,因为接口地址不可用. 这里只是给大家介绍一个过程,同时留作自己的笔记.如果要学习,可以参照别人的实例.比较好. ①选择项目根目录的src ,右键,new --> webservice client 然后输入地址: http://172.18.100.52:456/hello?wsdl 必须要加wsdl结尾,这样才是一个webservice的接口. finlish.这时候刷新项目.可以看到项目下/src/com

JNI之JAVA调用C++接口

1.JNI定义(来自百度百科) JNI是Java Native Interface的缩写,中文为JAVA本地调用.从Java1.1开始,Java Native Interface(JNI)标准成为java平台的一部分,它允许Java代码和其他语言写的代码进行交互.JNI一开始是为了本地已编译语言,尤其是C和C++而设计的,但是它并不妨碍你使用其他语言,只要调用约定受支持就可以了. 2.java通过JNI调用c++接口步骤 1).创建java包.类 此处创建 包myJNI,类TestJNI pac

java调用wsdl接口

前提: ① 已经提供了一个wsdl接口 ② 该接口能正常调用 步骤1:使用cxf的wsdl2java工具生成本地类 下载CXF:http://cxf.apache.org/download.html 配置环境变量: CXF_HOME=E:\WebService\CXF\apache-cxf-2.1.1\apache-cxf-2.1.1 PATH后追加上“ ;%CXF_HOME%\bin” 验证:cmd命令行中输入wsdl2java,如果显示其用法表示配置好了. 运行命令 : wsdl2java 

Java 调用 php接口(Ajax)(二)

由于项目里面需要用到Java调用PHP的充值接口,所以学习了一下,以下这个Demo是个小小的例子,写下来做个笔记> jsp页面: <%@ page language="java" import="java.util.*" pageEncoding="utf-8" contentType="text/html; charset=GBK"%> <% String path = request.getCont

java 调用webservice接口wsdl,推荐使用wsdl2java,放弃wsimport

网上说wsimport是jdk1.6后自带的客户端生成调用webservice接口的工具,其实我挺喜欢原生的东西,毕竟自家的东西用着应该最顺手啊,但往往让人惊艳的是那些集成工具. 本机jdk1.8.1的,直接按网上说的wsimport -keep -p wsimport.test http://****:****/***.wsdl 报警报错,报警warning可以忽略,但错误error 难以解决,说具有相同名称 "xxx" 的类/接口已在使用.请使用类定制设置来解决此冲突.找了许多资料

java调用http接口并返回json对象

1 import java.io.BufferedReader; 2 import java.io.InputStreamReader; 3 import java.io.OutputStreamWriter; 4 import java.io.PrintWriter; 5 import java.net.URL; 6 import java.net.URLConnection; 7 import java.net.URLEncoder; 8 import java.util.HashMap;