get请求代码(方法代码块),其余部分看自己喜好来!本人亲自测试过一定是通的
public void getAccessToken(String tmp_auth_code){
final String appId ="****************************";
final String APPSECRET ="*******************";
String token = "https://oapi.*******.com/sns/***?appid="+appId+"&**="+APPSECRET;
BufferedReader reader = null;
StringBuffer buffer = new StringBuffer();
System.setProperty("sun.net.client.defaultConnectTimeout", String.valueOf(10000));// (单位:毫秒)
System.setProperty("sun.net.client.defaultReadTimeout", String.valueOf(10000)); // (单位:毫秒)
try{
URL url = new URL(token);
URLConnection urlConnect = url.openConnection();
urlConnect.setRequestProperty("accept", "*/*");
urlConnect.setRequestProperty("connection", "Keep-Alive");
urlConnect.setConnectTimeout(5000);
urlConnect.setReadTimeout(1000);
urlConnect.connect();
reader = new BufferedReader(new InputStreamReader(urlConnect.getInputStream()));
String line;
String ss = IOUtils.toString(reader);
JSONObject obj =JSONObject.parseObject(ss);
String access_token = obj.getString("***********");
getUserinfo(tmp_auth_code,access_token);
/* while((line = reader.readLine())!=null){
buffer.append(line);
}
System.out.println(buffer.toString());
*/
}catch(Exception e){
e.printStackTrace();
}
finally{
try{
if(reader != null)
reader.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
Post请求代码(方法块),本人亲自测试过一定是通的
public void getUserinfo(String tmp_auth_code,String access_token){
String userInfo = "https://o*8.***.com/sns/get_persistent_code?acc*******=*********_TOKEN";
userInfo = userInfo.replace("ACCESS_TOKEN", access_token);
try{
URL urlPost = new URL(userInfo);
HttpURLConnection httpconnect = (HttpURLConnection)urlPost.openConnection();
httpconnect.setDoOutput(true);
httpconnect.setDoInput(true);
httpconnect.setUseCaches(false);
httpconnect.setInstanceFollowRedirects(false);
httpconnect.setRequestMethod("POST");//此处代码必须大写不能小写注意别采坑
httpconnect.setRequestProperty("Accept", "application/json");
httpconnect.setRequestProperty("Content-Type", "application/json");
httpconnect.connect();
OutputStreamWriter output = new OutputStreamWriter(httpconnect.getOutputStream(),"UTF-8");
JSONObject json = new JSONObject();
json.put("tmp_auth_code", tmp_auth_code);
output.append(json.toJSONString());
output.flush();
output.close();
InputStream input;
int code = httpconnect.getResponseCode();
if(code == 200){
input = httpconnect.getInputStream();
}else{
input = httpconnect.getErrorStream();
}
String xxx = IOUtils.toString(input);//采用这个方法就可以免掉if()那一坨代码块,这个方法是大佬告知我才苏学浅肯定是不知道的了
JSONObject obj =JSONObject.parseObject(xxx);
int length =(int) httpconnect.getContentLength();
int line =0;
if(length!=0){//可以不要
byte[] date = new byte[length];
while((line =input.read(date))!=-1){
}
String result = new String(date,"UTF-8");
System.out.println(result);
}*/
}catch(Exception e){
}
}