HttpURLConnection编写方法
来源:互联网 发布:网络机柜 编辑:程序博客网 时间:2024/06/05 10:19
public class MainActivity extends Activity {
// String path = "http://op.juhe.cn/onebox/news/query?q=普京盟友炮轰OPEC不团结 称其影响油市的时代已终结&key=f2219bf102195209a3db41a58ce0b180";
String path = "http://web.juhe.cn:8080/constellation/getAll";
//给服务器传递的参数
String str="consName=狮子座&type=today&key=3ac9f31ff66b9746539472887b3799c3";
Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {};
};
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
new Thread() {
public void run() {
geData();
};
}.start();
}
/**
*
*/
private void geData() {
// 设置接口地址
try {
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
// 设置连接超时
connection.setConnectTimeout(5000);
// 设置读取超时
connection.setReadTimeout(5000);
// 设置请求方式
connection.setRequestMethod("POST");
//得到输出流,象服务器传递参数
OutputStream outputStream = connection.getOutputStream();
PrintWriter printWriter=new PrintWriter(outputStream);
//设置要传递的数据
printWriter.println(str);
printWriter.flush();
// 连接网络
connection.connect();
// 如果响应码等于200代表请求成功
if (connection.getResponseCode() == 200) {
// 得到服务器返回的信息,是流的形式返回回来的
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream, "UTF-8"));
String str;
StringBuffer stringBuffer = new StringBuffer();
// 一次读一行
while ((str = bufferedReader.readLine()) != null) {
// 把读到的每一行信息都追加到stringBuffer里
stringBuffer.append(str);
}
String data = stringBuffer.toString();
// System.out.println(data);
// 将json数据转成对象
Gson gson = new Gson();
Bean bean = gson.fromJson(data, Bean.class);
System.out.println(bean.toString());
// 把对象通过handler发送给主线程
Message msg = Message.obtain();
// msg.obj = root;
// handler.sendMessage(msg);
} else {
Toast.makeText(this, " 请求失败 ", 0).show();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
- HttpURLConnection编写方法
- java编写http请求:HttpURLConnection
- HttpURLConnection 的 POST 方法
- HttpURLConnection-Post方法实现
- HttpURLConnection-Get方法实现
- HttpURLConnection getResponseCode()方法阻塞
- HttpURLConnection方法之setRequestProperty()浅谈
- HttpURLConnection对象相关方法操作
- HttpURLConnection
- HttpURLConnection
- HttpURLConnection
- httpurlconnection
- HttpURLConnection
- HttpURLConnection
- HttpURLConnection
- HttpURLConnection
- HttpURLConnection
- HttpURLConnection
- 另类阻止驱动加载
- Ubuntu:unknown filesystem
- hdu 1671
- LeetCode-1.Two Sum
- Gym 100712J Candy
- HttpURLConnection编写方法
- 虚拟云平台网址
- 如何利用Google成为一个更好的程序员
- Debian中如何切换默认Python版本
- 框架知识(2)--iBatis基础知识
- 破译A盾禁止加载驱动失效之谜
- 数据结构上机测试2-2:单链表操作B
- rsync 使用示例
- STL 简单 vector 的实现