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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM