HttpRequestUtils類
用於方便進行http請求
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
/**
* @author cimo
*/
public class HttpRequestUtils {
/**
* 向指定 URL 發送POST方法的請求
*
* @param url 發送請求的 URL
* @param param 請求參數,請求參數應該是 name1=value1&name2=value2 的形式。
* @return 所代表遠程資源的響應結果
*/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打開和URL之間的連接
URLConnection conn = realUrl.openConnection();
// 設置通用的請求屬性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("Content-type", "application/json");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setReadTimeout(15000);
// 發送POST請求必須設置如下兩行
conn.setDoOutput(true);
conn.setDoInput(true);
// 獲取URLConnection對象對應的輸出流
out = new PrintWriter(conn.getOutputStream());
// 發送請求參數
out.print(param);
// flush輸出流的緩衝
out.flush();
// 定義BufferedReader輸入流來讀取URL的響應
in = new BufferedReader( new InputStreamReader(conn.getInputStream(),"utf-8") );
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("發送 POST 請求出現異常!"+e);
e.printStackTrace();
}
//使用finally塊來關閉輸出流、輸入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
/**
* 向指定URL發送GET方法的請求
*
* @param url 發送請求的URL
* @return URL 所代表遠程資源的響應結果
*/
public static String sendGet(String url) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url;
URL realUrl = new URL(urlNameString);
// 打開和URL之間的連接
URLConnection connection = realUrl.openConnection();
// 設置通用的請求屬性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立實際的連接
connection.connect();
// 定義 BufferedReader輸入流來讀取URL的響應
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("發送GET請求出現異常!" + e);
e.printStackTrace();
}
// 使用finally塊來關閉輸入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
* 將字符串轉換成map
* @param responseEntity map字符串
* @return map對象
*/
public static Map<String,String> getMap(String responseEntity) {
Map<String, String> map = new HashMap<>();
// 以&來解析字符串
String[] result = responseEntity.split("\\&");
for (String str : result) {
// 以=來解析字符串
String[] split = str.split("=");
// 將字符串存入map中
if (split.length == 1) {
map.put(split[0], null);
} else {
map.put(split[0], split[1]);
}
}
return map;
}
}
GithubConfig類
用於保存Github授權信息配置文件
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
/**
* @author cimo
*/
public class GithubConfig {
/**
* github授權的 Client ID
*/
private static final String CLIENT_ID = "你的 Client ID";
/**
* github授權的 Client Secret
*/
private static final String CLIENT_SECRET = "你的 Client Secret";
/**
* 結果回調地址
*/
private static final String CALLBACK_URL = "你在Github上填寫的回調地址";
/**
* 獲取code的url
*/
public static final String CODE_URL = "https://github.com/login/oauth/authorize?client_id="+CLIENT_ID;
/**
* @param code 獲取到的code
* @return 獲取token的url
*/
public static String getTokenUrl(String code) {
return "https://github.com/login/oauth/access_token?client_id="+CLIENT_ID+"&client_secret="+CLIENT_SECRET+"&code="+code+"&redirect_uri="+CALLBACK_URL;
}
/**
* @param token 獲取到的token
* @return 通過token獲取github用戶信息
*/
public static String getUerInfoUrl(String token) throws IOException {
String result = "";
BufferedReader in = null;
try {
String baseUrl = "https://api.github.com/user";
URL realUrl = new URL(baseUrl);
// 打開和URL之間的連接
URLConnection connection = realUrl.openConnection();
//將token加入請求頭
connection.setRequestProperty("Authorization","token "+token);
// 建立實際的連接
connection.connect();
// 定義 BufferedReader輸入流來讀取URL的響應
in = new BufferedReader(new InputStreamReader( connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("發送token請求出現異常!" + e);
e.printStackTrace();
}
// 使用finally塊來關閉輸入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
}
發出請求後回調的地址
這裏爲了方便一點用servlet實現
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
/**
* @author cimo
*/
@WebServlet(name = "GithubLogingCallBack")
public class GithubLogingCallBack extends javax.servlet.http.HttpServlet {
@Override
protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
}
@Override
protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
//獲取code地址:https://github.com/login/oauth/authorize?client_id=你的client_id
String code = request.getParameter("code");
System.out.println("code:"+code);
//申請令牌
String result = HttpRequestUtils.sendGet( GithubConfig.getTokenUrl(code) );
System.out.println("result:"+result);
//從result中截取令牌
String access_token = HttpRequestUtils.getMap(result).get("access_token");
System.out.println("access_token:"+access_token);
//通過令牌獲取用戶信息
String userInfo = GithubConfig.getUerInfoUrl(access_token);
System.out.println("用戶信息:"+userInfo);
//將token加入響應頭,並返回用戶信息
response.setHeader("Authorization","token "+accessToken);
response.getWriter().println(userInfo);
}
}