HttpURLConnetionDemo
来源:互联网 发布:网络现在做什么挣钱 编辑:程序博客网 时间:2024/06/09 14:59
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void btnForGet(View view){
new Thread(){
@Override
public void run() {
getHealthForGet();
}
}.start();
}
public void btnForPost(View view){
new Thread(){
@Override
public void run() {
getHealthForPost();
}
}.start();
}
/**
* 使用HttpURLConnection请求数据
* 请求方式 : POST
*/
private void getHealthForPost(){
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);
//设置请求参数
OutputStream os = connection.getOutputStream();
os.write(("key=eb033dfcf95c03f9f451f6973049e6be").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();
}
}
/**
* 使用HttpURLConnection获取数据
* API
* 请求方式 : get
*/
private void getHealthForGet(){
try {
//创建URL
URL url = new URL("http://japi.juhe.cn/health_knowledge/categoryList?key=eb033dfcf95c03f9f451f6973049e6be");
//敲回车
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();
}
}
}
阅读全文
0 0
- HttpURLConnetionDemo
- Sliding Window
- linux启动流程
- Java 3.1 java流程控制之循环语句
- 插入排序(insert sort)
- bzoj2028 [SHOI2009]会场预约(set)
- HttpURLConnetionDemo
- Lesson02_C#基础_part01
- Linux 6个最小化原则讲解
- XYNUOJ 问题 F: 小希的迷宫
- Python PIP Install throws TypeError: unsupported operand type(s) for -=: 'Retry' and 'int'
- linux之通配符和正则表达式
- POJ 2528-posters(线段树区间染色+离散化)
- [UVALive 7670] Asa's Chess Problem
- 1.13 C# 集合(非泛型)