在主活动类中,调用一个线程访问网络(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. Tomcat发布项目方法

    第一种方法:    将已完成的项目(无论用jbuilder\eclipse\netbeans)下的webroot目录整个拷贝到Tomcat的webapps目录中,假若webroot目录改名为xxx,则 ...

  2. wex5 实战 框架拓展之2 事件派发与data刷新

    一 前言 讲完公共data,相信大家对框架级的data组件级绑定有了更新的认识,接下来我们继续深入,以求研究明白wex5的框架能力. 在一个web项目中,其实有一个data, 是基础框架必须的data ...

  3. Navicat for MySQL安装之后不知道登录密码

    1,关闭你现在正在运行的mysql数据库,关闭mysql服务器. 2,关闭数据库后,运行点击开始运行,输入cmd进入命令行窗口,在这个命令行中操作进入到你数据库所在的安装路径,一般默认安装的话都会在e ...

  4. asp的gridview

    using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI ...

  5. C# Socket编程笔记

    1.按惯例先来介绍下socket      Windows中的很多东西都是从Unix领域借鉴过来的,Socket也是一样.在Unix中,socket代表了一种文件描述符(在Unix中一切都是以文件为单 ...

  6. mariadb:InnoDB: Error: log file ./ib_logfile0 is of different size 0 5242880 bytes

    mariadb 启动中 InnoDB: Error: log file ./ib_logfile0 is of different size 0 起因:线上正在运行的系统,因为需要调整性能,变更了my ...

  7. JavaScript parseInt() 函数

    定义和用法 parseInt() 函数可解析一个字符串,并返回一个整数. 语法 parseInt(string, radix) 参数 描述 string 必需.要被解析的字符串. radix 可选.表 ...

  8. EasyUI、Struts2、Hibernate、spring 框架整合

    经历了四个月的学习,中间过程曲折离奇,好在坚持下来了,也到了最后框架的整合中间过程也只有自己能体会了. 接下来开始说一下整合中的问题和技巧: 1,  jar包导入 c3p0(2个).jdbc(1个). ...

  9. dsp28377控制DM9000收发数据——第三版程序,通过外部引脚触发来实现中断接受数据,优化掉帧现象

    //-------------------------------------------------------------------------------------------- - //D ...

  10. 如何用photoshop把图片白色背景变成透明?

    1.当提示配置文件丢失时,选择“指定RGB模式”. 2.Ctrl+J是一个复合动作,复制+新建,会得到一个新图层. 3.选中新图层,点击鼠标左边工具条里面的魔棒工具,再用鼠标点击下图片的某处白色部分, ...