android post 方式 访问网络 实例

  • android post 方式 访问网络 实例

因为Android4.0之后对使用网络有特殊要求,已经无法再在主线程中访问网络了,必须使用多线程访问的模式

该实例需要在android配置文件中添加 网络访问权限

<uses-permission android:name="android.permission.INTERNET"/>

android版本 最低API

<uses-sdk  android:minSdkVersion="9"  android:targetSdkVersion="17" />

package com.app.urltest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.view.Menu;
import android.widget.TextView; public class MainActivity extends Activity {
TextView textView;
// 网络地址
String urlPath = "http://webservice.webxml.com.cn/WebServices/TrainTimeWebService.asmx"
+ "/getStationAndTimeByStationName";
// 请求参数
String requestStr = "StartStation=北京&ArriveStation=上海&UserID=";
/*
* 网络连接 讲uripath 转换成URL对象 连接请求 需用 URL对象的openConnection
* 方法得到一个连接对象httpUrlConnection 设置请求参数: 超时 请求方式 读写 内容类型 长度 ... 发送请求参数:得到输出流
* 吧请求参数写到输出流 服务器响应: 从响应 (输入)流中得到 数据 需用ANdroidManifest中添加 访问网络权限
*/
public String connectNework() { try {
// 创建URL
URL url = new URL(urlPath);
// 获得连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求参数
connection.setReadTimeout(3000);// 超时
connection.setRequestMethod("POST");// 请求方式
connection.setDoInput(true);// 可读写
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");// 设置请求 参数类型
byte[] sendData = requestStr.getBytes("UTF-8");// 将请求字符串转成UTF-8格式的字节数组
connection.setRequestProperty("Content-Length", sendData.length
+ "");// 请求参数的长度 OutputStream outputStream = connection.getOutputStream();// 得到输出流对象
outputStream.write(sendData);// 发送写入数据 /*//获得 服务器响应代码
int code = connection.getResponseCode();
if(code==20){
//获取数据
}
*/
// 响应
InputStream inputStream = connection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader bReader = new BufferedReader(inputStreamReader);
String str = "";
String temp = "";
while ((temp = bReader.readLine()) != null) {
str = str + temp + "\n";
}
return str;// 返回响应数据 } catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
} @Override
protected void onCreate(Bundle savedInstanceState) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyLog()
.penaltyDialog() ////打印logcat,当然也可以定位到dropbox,通过文件保存相应的log
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll()
.penaltyLog()
.build()); super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView1);
new Thread(runnable).start(); }
String text;
//使用Handler 对象更新主UI
Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
/*方式二: 使用Bundle接收数据
* Bundle data = new Bundle()
* String text =data.getString("s",s);
*
*/
//显示到控件
textView.setText(text); };
};
Runnable runnable = new Runnable() { @Override
public void run() {
//连接网络请求
text = connectNework();
Message msg = new Message();
/* 使用Bundle对象 传送数据
* Bundle data = new Bundle();
* data.putString("s",s);
* msg.setData(data);
*
*/
handler.sendMessage(msg);
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
} }
  • Apche接口实现 访问网络
Apche HttpClient 是一个开源项目,从名字上就可以看出,它是一个简单的HTTP客户端(并不是浏览器),可以发送HTTP请求,接受HTTP响应。但是不会缓存服务器的响应,不能执行HTTP页面中签入嵌入的JS代码,自然也不会对页面内容进行任何解析、处理,这些都是需要开发人员来完成的。

  现在Android已经成功集成了HttpClient,所以开发人员在Android项目中可以直接使用HttpClient来想Web站点提交请求以及接受响应,如果使用其他的Java项目,需要引入进相应的Jar包。HttpClient可以在官网上下载:http://hc.apache.org/downloads.cgi
下面来看一个简单的应用 访问网络的例子.
package com.app.apachehttpclient;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List; import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils; import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.widget.TextView; public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectAll().penaltyLog().penaltyDialog() // //打印logcat,当然也可以定位到dropbox,通过文件保存相应的log
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll()
.penaltyLog().build());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String url_service = "http://webservice.webxml.com.cn/WebServices/TrainTimeWebService.asmx"
+ "/getStationAndTimeByStationName";
// 创建一个请求
HttpPost httpPost = new HttpPost(url_service);
List params = new ArrayList();
// 设置参数
params.add(new BasicNameValuePair("StartStation", "北京"));// 始发站
params.add(new BasicNameValuePair("ArriveStation", "上海"));// 到达站
params.add(new BasicNameValuePair("UserID", ""));// 用户ID
try {
// 设置编码
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
// 发送请求 并获得反馈
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(httpPost);
// 解析返回的数据
if (httpResponse.getStatusLine().getStatusCode() != 404) {//判断服务器状态
String result = EntityUtils.toString(httpResponse.getEntity());
System.out.println(result);
// 显示到控件
TextView textView1 = (TextView) findViewById(R.id.textView1);
textView1.setText(result);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
上一篇:SQL SERVER 查看数据库表的字段类型,是否允许为NULL,默认值,主键等


下一篇:详解coredump