private void getHealthInfoForGet(){
try {
//填入请求地址
URL url = new URL("http://japi.juhe.cn/health_knowledge/categoryList?key=eb033dfcf95c03f9f451f697
3049e6be");
//打开链接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//设置请求方式
connection.setRequestMethod("GET");
//设置连接服务的时间
connection.setConnectTimeout(5 * 1000);
//设置读取服务返回的数据的时间
connection.setReadTimeout(5 * 1000);
//等待服务器响应
//得到服务的响应码
int code = connection.getResponseCode();
if(code == 200){//判断服务是否响应成功
//读取服务器所放回来的数据信息
InputStream is = connection.getInputStream();
String info = StreamTools.readFromNetWork(is);
System.out.println("结果 : "+info);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void getHealthInfoForPost(){
try {
URL url = new URL("http://japi.juhe.cn/health_knowledge/categoryList");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//一定要大写
connection.setRequestMethod("POST");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
//设置请求参数 (POST)
OutputStream os = connection.getOutputStream();
os.write(("key=eb033dfcf95c03f9f451f697
3049e6be").getBytes());
os.flush();
//等待服务器响应
int code = connection.getResponseCode();
if(code == 200){
//获取服务器的内容
InputStream is = connection.getInputStream();
String info = StreamTools.readFromNetWork(is);
System.out.println("-->"+info);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public class StreamTools {
public static String readFromNetWork(InputStream is){
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1){
baos.write(buffer,0,len);
}
return baos.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}