1.首先创建一个工具类
public class ConTools {
private HttpURLConnection connection;
/**
* TangRen 2016-4-9 下午3:11:28
*/
public HttpURLConnection ConTools(String urlString) {
try {
URL url = new URL(urlString);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type",
"application/json; encoding=UTF-8");
connection.connect();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return connection;
}
}
Read工具类
public class ReadTools {
/**
* TangRen 2016-4-9 下午3:22:23
*/
private BufferedReader reader;
private StringBuffer sb;
public StringBuffer ReadTools(HttpURLConnection connection) {
try {
reader = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
sb = new StringBuffer("");
while ((line = reader.readLine()) != null) {
line = new String(line.getBytes(), "UTF-8");
sb.append(line);
}
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sb;
}
}
接下来就是申请TOKEN
public class ApplyToken {
/**
* @param args
* @author TangRen
* @date 2016-4-14 上午9:41:19
*/
private static ReadTools read;
private static HttpURLConnection connection;
static StringBuffer readTools = null;
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplyToken();
}
public static String ApplyToken() {
// TODO Auto-generated constructor stub
try {
URL url = new URL(AppURL.url_applytoken);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type",
"application/json; encoding=UTF-8");
connection.connect();
DataOutputStream outputStream=new DataOutputStream(connection.getOutputStream());
BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
writer.flush();
writer.close();
read = new ReadTools();
readTools = read.ReadTools(connection);
System.out.println(readTools);
// 断开连接
connection.disconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return readTools.toString();
}
}