在主活动类中,调用一个线程访问网络(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"/>

android 使用httpclient访问网络的更多相关文章

  1. android post 方式 访问网络 实例

    android post 方式 访问网络 实例 因为Android4.0之后对使用网络有特殊要求,已经无法再在主线程中访问网络了,必须使用多线程访问的模式 该实例需要在android配置文件中添加 网 ...

  2. HttpClient访问网络

    HttpClient项目时Apache提供用于访问网络的类,对访问网络的方法进行了封装.在HttpURlConnection类中的输入输出操作,统一封装成HttpGet.HttpPost.HttpRe ...

  3. Android 多线程通信 访问网络

    package org.rongguang.testthread; import android.app.Activity; import android.os.Bundle; import andr ...

  4. Android 使用 HTTP 协议访问网络

    正在看<第一行代码>,记录一下使用 HTTP 协议访问网络的内容吧! 在Android发送Http请求有两种方式,HttpURLConnection和HttpClient. 1.使用Htt ...

  5. Android访问网络(可以正常使用)

    以下是MainActiviy.java,有必要的注释,里面用到了handler,以及线程,workThread如何更新mainThread才能够更新的内容. package com.wyl.httpt ...

  6. Android访问网络

    Android中访问网络用的是HttpClient的方式,即Apache提供的一个jar包.安卓中继承了改jar包,所以安卓adt中不需要专门import该jar,直接就可以使用. 以下是MainAc ...

  7. Android O 可以上网 提示无法访问网络

    android O连接Wifi,可以上网,但是却提示无法访问网络,并且在wifi图标上有一个'x'. 从android N开始引入了监控机制,每次连接都会访问一下google的服务器,由于国内被墙,所 ...

  8. Android使用Http协议访问网络——HttpConnection

    套路篇 使用HttpConnection访问网络一般有如下的套路: 1.获取到HttpConnection的实例,new出一个URL对象,并传入目标的网址,然后调用一下openConnection() ...

  9. 使用HTTP协议访问网络(Android)

    在做项目的过程中需要连接服务器访问数据,还没有接触过Android网络编程方面,参考了<Android第一行代码>,在做的过程中遇到了很多的问题,这里就此记录一下. 先给出访问网络的代码: ...

随机推荐

  1. 删除变长列字段后使用DBCC CLEANTABLE回收空间

    标签:SQL Server Reclaim space 收缩表 原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://lzf328.bl ...

  2. Oracle学习笔记(1)----忘记用户名的密码该如何找回

    (1)在连接数据库之前需要打开如下服务: (2)如果忘记用户的密码 I:打开cmd窗口 II:键入命令:connect / as sysdba; III:alter user 用户名 identifi ...

  3. Cocos2dx3.11.1Android播放视频,后台 黑屏,无法记忆播放bug修改

    /* * Copyright (C) 2006 The Android Open Source Project * Copyright (c) 2014 Chukong Technologies In ...

  4. fiddler如何修改request header

    在命令行中输入命令:  bpu www.baidu.com   (这种方法只会中断www.baidu.com) 然后刷新网站,在fiddler中点击被打断的网址,点击Inspectors—>Ra ...

  5. Java项目多数据源配置

    由于种种原因,有的时候可能要连接别人的数据库,或者不同的数据库没法自动转换,重构起来数据量又太大了,我们不得不在一个项目中连接多个数据源.从网上找了各种资料,只有这位大神给出的解决方案一下子就成功了. ...

  6. python学习之迭代器与生成器

    1.迭代器省内存 迭代器只允许往后读数据,不允许回读数据 迭代器不能跳着读文件,因为他是一点一点加载文件内容到内存的,读完了可以销毁或丢掉 2.生成一个迭代器 a = iter(["fd&q ...

  7. js正则表达式

    正则表达式分析页面:https://regexper.com/ 可以很清楚的分析正则,加深理解 var reg=/\bis\b/; 'He is a boy.This is a dog.Where i ...

  8. Python3基础 访问列表指定索引值的元素

    镇场诗:---大梦谁觉,水月中建博客.百千磨难,才知世事无常.---今持佛语,技术无量愿学.愿尽所学,铸一良心博客.------------------------------------------ ...

  9. yum安装命令的使用方法

    yum安装常用软件的命令 #yum check-update #yum remove 软件包名 #yum install 软件包名 #yum update 软件包名 yum命令常见使用方法 yum - ...

  10. 3d游戏模型及地形提取及导航

    支持所有DirectX的游戏模型提取 有需要的可以直接联系我!QQ290387340