Android中进行基于 HTTP协议的网络访问

来源:互联网 发布:手机有些软件打不开 编辑:程序博客网 时间:2024/06/08 10:06

Android中进行基于 HTTP协议的网络访问

HttpClient  (Apache开发)--->以下简称HC

HttpURLConnection(Google在发布Android时在Java基础上修改得到的)-->以下简称UC

使用上面两种方法访问网络的基本步骤:

0.....申请权限  INTERNET访问权限(Android对权限要求很严谨的)

1..任何网络访问的相关代码,必须在工作线程中执行(必须....)

2..创建HC/UC对象

HttpClient client=new DefaultHttpClient();


      HtttpURLConnection connection =(HttpURLConnection) new     URL("http://172.22.122.122:8080/xxx/xxx.xxx").openConnection();

3..声明发起网络访问的方式(GET/POST)

     HttpPost post =new HttpPost("http://172.22.122.122:8080/xxx/xxx.xxx")

     HttpGet get = new HttpGet("http://172.22.122.122:8080/xxx/xxx.xxx");

    connection.setRequestMethod("POST/GET");

4..进行网络连接

     HttpResponse resp=client.execute(post);

     connection.connect();


5..获得服务器响应的结果

     String result=EntityUtils.toString(resp.getEntiry());

     String result=new BufferedReader(new InputStreamReader(connection. InputStream())).readLine();

6..解析结果,提取需要的内容

7..解析结果要提交到UI线程进行呈现



利用HttpClient的POST方式发起带参数的请求
利用POST方式发起请求,参数要放到请求实体中,并且在请求头中添加对实体中参数的说明。

添加说明:
post.setHeader("Content-Type", "application/x-www-form-urlencoded");

添加参数:
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("loginname", user.getName()));
parameters.add(new BasicNameValuePair("password", user.getPassword()));
parameters.add(new BasicNameValuePair("realname", user.getRealname()));
parameters.add(new BasicNameValuePair("email", user.getEmail()));
HttpEntity entity = new UrlEncodedFormEntity(parameters);
post.setEntity(entity);

0 0
原创粉丝点击