android 使用httpclient访问网络

在主活动类中,调用一个线程访问网络(android4.0以上耗时的操作不能放在主线程中):
 
 
 
//声明两个Button对象,与一个TextView对象
private TextView mTextView1;
private Button mButton1, mButton2; private static final int MSG_SUCCESS = 0;
private static final int MSG_FAILURE = 1;
private Thread mThread;//在android4.0及以上,非UI操作放在主线程会报错,因此在这里获取网络数据需要开启一个线程 private Handler myHandler = new Handler(){
public void handleMessage(Message msg){//此方法在Ui线程执行
switch(msg.what){
case MSG_SUCCESS:
mTextView1.setText("成功!返回数据:");
mTextView1.append(msg.toString());
break;
case MSG_FAILURE:
Toast.makeText(MainActivity.this, "网络异常", 1).show();
break;
} }
}; Runnable runnable = new Runnable(){
@Override
public void run() {//在新的线程中执行
//声明网址字符串
String uriAPI = "http://192.168.1.102:8080/AndroidDemo/demo.html";
// 创建Http post连接
HttpPost httpRequest = new HttpPost(uriAPI);
// post 运行传送变量必须用NameValuePair[]数组存车场
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("str", "I am a Post String"));
try {
// 发送Http request
httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
// 取得Http response
HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
// 若状态码为200
if (httpResponse.getStatusLine().getStatusCode() == 200) {
// 取出应答字符串
String strResult = EntityUtils.toString(httpResponse.getEntity());
Log.e("返回信息", strResult);
// mTextView1.setText(strResult);
Message msg = Message.obtain();
msg.obj = strResult;
msg.arg1 = MSG_SUCCESS;
myHandler.sendMessage(msg);
} else {
Log.e("返回信息", String.valueOf(httpResponse.getStatusLine().getStatusCode()));
// mTextView1.setText("Error Response: " + httpResponse.getStatusLine().toString());
}
} catch (ClientProtocolException e) {
// mTextView1.setText(e.getMessage().toString());
e.printStackTrace();
} catch (IOException e) {
// mTextView1.setText(e.getMessage().toString());
e.printStackTrace();
} catch (Exception e) {
// mTextView1.setText("异常");
e.printStackTrace();
}
} }; @Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main); // 通过findviewbyid构造器创建TextView与button对象
mButton1 = (Button) this.findViewById(R.id.get);
mButton2 = (Button) this.findViewById(R.id.post);
mTextView1 = (TextView) this.findViewById(R.id.text);
//设置Onclicklistener来监听onclick事件
mButton1.setOnClickListener(this);
mButton2.setOnClickListener(this);
}
@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;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
//自定义字符串替换函数
public String eregi_replace(String strFrom, String strTo, String strTarget) {
String strPattern = "(?i)" + strFrom;
Pattern p = Pattern.compile(strPattern);
Matcher m = p.matcher(strTarget);
if (m.find()) {
return strTarget.replaceAll(strFrom, strTo);
} else {
return strTarget;
}
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.get:
/*
// 声明网址字符串
String uriAPI1 = "http://39.191.72.9:8080/AndroidDemo/demo.html";
//创建Http Get连接
HttpGet httpRequest1 = new HttpGet(uriAPI1);
try {
//发送Http Request
HttpResponse httpResponse1 = new DefaultHttpClient().execute(httpRequest1);
//若状态码为200
if (httpResponse1.getStatusLine().getStatusCode() == 200) {
//取出应答字符串
String strResult1 = EntityUtils.toString(httpResponse1.getEntity());
//删除多余字符
strResult1 = eregi_replace("(\r\n|\r|\n|\n\r)", "", strResult1);
mTextView1.setText("成功!返回数据:");
mTextView1.append(strResult1);
}
} catch (ClientProtocolException e) {
mTextView1.setText("异常");
e.printStackTrace();
} catch (IOException e) {
mTextView1.setText("异常");
e.printStackTrace();
} catch (Exception e) {
mTextView1.setText("异常");
e.printStackTrace();
}
*/
break;
case R.id.post:
// if(mThread == null){
mThread = new Thread(runnable);
mThread.start();
//}
//else{
//Toast.makeText(MainActivity.this, "系统异常", 1).show();
//}
break;
} }
 
 
 
xml文件中布局:
 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.httpdemo.app.MainActivity">
<Button
android:id="@+id/get"
android:text="GET获取数据"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/post"
android:text="POST获取数据"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
 
 
访问网络需要网络权限:
 
<uses-permission android:name="android.permission.INTERNET"/>
上一篇:高效使用git的一些命令


下一篇:易酷CMS2.5本地文件包含漏洞复现