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);
}
}