在主活动类中,调用一个线程访问网络(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. Linux下面配置文件~/.bash_profile

    ~/.的意义是什么? ~ 代表你的/home/用户名目录 假设你的用户名是x,那么~/就是/home/x/ . 是代表此目录本身,但是一般可以不写 所以cd ~/. 和cd ~ 和cd ~/效果是一样 ...

  2. jquery mobile tabs

    https://github.com/groovetrain/jQuery.mobile-Tabs

  3. HDU 1072 Nightmare

    Description Ignatius had a nightmare last night. He found himself in a labyrinth with a time bomb on ...

  4. C# 调用Excel 出现服务器出现意外情况. (异常来自 HRESULT:0x80010105 (RPC_E_SERVERFAULT)

    C# 调用Excel 出现服务器出现意外情况. (异常来自 HRESULT:0x80010105 (RPC_E_SERVERFAULT) private Microsoft.Office.Intero ...

  5. 我的CSS布局之旅--持续更新

    虽然我也接触前端一年之久了,但是无奈从切图布局下来的经验还真是很不足,因为之前比赛或者是做小项目时全部都是自己负责设计,所以都是编写边设计,哎呀,也是醉了:或者是有模板,然后从人家上面扒拉下来的,真的 ...

  6. java内存详解

    二.JAVA中的内存模型 程序运行的时候,内存主要由以下部分组成: 堆:所有线程共享一个堆:存放的都是new 出来的对象:由垃圾回收器回收: 方法区:所有线程共享一个方法区:里面存放的内容有点杂,可以 ...

  7. c++中函数中变量内存分配以及返回指针、引用类型的思考

    众所周知,我们在编程的时候经常会在函数中声明局部变量(包括普通类型的变量.指针.引用等等). 同时,为了满足程序功能的需要,函数的返回值也经常是指针类型或是引用类型,而这返回的指针或是引用也经常指向函 ...

  8. Hibernate的映射组件属性

    组件属性 如果持久化类的属性并不是基本数据类型,也不是一个日期或者字符串常量,而是一个复合类型的对象,例如 private Name name; 那么这就是一个组件属性. 组件属性可以是任何普通的ja ...

  9. 【leetcode❤python】 168. Excel Sheet Column Title

    class Solution(object):    def convertToTitle(self, n):        """        :type n: in ...

  10. 7. Swift 基于Xmpp和openfire实现一个简单的登录注册

    1. 基本步骤:首先导入Xmpp框架,配置环境 ->由于我们使用的是OC的Xmpp框架,再进行Swift开发时需要进行桥接. 具体方法就是创建一个基于c的.h的头文件,然后将我们需要编译OC的语 ...