Android网络编程之URLConnection和HttpClient访问服务器
来源:互联网 发布:最短路径算法原理 编辑:程序博客网 时间:2024/05/09 00:34
现在不管什么应用几乎都不是独立存在的,基本都是互联网中的一员,如何成为其中的一员呢?首先我们能接入互联网,使用互联网资源,分享互联网资源。今天我们来介绍的是如何在Android程序中使用java自带的URLConnection和apache的方法HttpClient方法访问服务器,请求资源。
在前面几篇文章中已经为这篇文章做了很充分的准备,有服务端的搭建,帮助我们进行通信测试,有IO的介绍,连接完成之后交换数据,还有各种协议的介绍,深入了解网络的意义。在这里我假设各位都已经做好了充分的准备,我这这里就只用一个搭建好的web项目jsp进行测试,jsp代码如下:
<%@page import="org.omg.CORBA.Request"%><%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%if(request.getParameter("hello") != null && request.getParameter("hello").equals("hello")){ out.print("Hello Hello"); } %>
下面开始代码讲解:
1. URLConnection:使用GET请求服务端。
new Thread() { public void run() { URLConnection uc; try { // ----------GET METHOD ------------------- uc = new URL( "http://172.16.10.18:8080/Servlet/index.jsp?hello=hello") .openConnection(); uc.setConnectTimeout(CONNECT_TIME_OUT); uc.setReadTimeout(READ_TIME_OUT); byte[] data = new byte[1024]; InputStream is = uc.getInputStream(); int len = 0; while ((len = is.read(data)) != -1) { sb.append(new String(data, 0, len)); } mHandler.sendEmptyMessage(VALIDATE_MSG); } catch (Exception e) { e.printStackTrace(); } } }.start();
网络请求代码放在Thread里面只是因为Android里面不能写在主线程里面,这个是个耗时的操作,属于不安全的操作,所以不能放在主线程影响界面的交互。在上面从服务器接收到的响应中,我们使用了最基础的inputstream 和 outputstream 进行数据的读取和写入,由于在这里只涉及到字符串的数据交换,所以我们在这里可以使用BufferedReader来操作更加方便,如下:
private StringBuffer sb = new StringBuffer();// ----------GET METHOD ------------------- uc = new URL( "http://172.16.10.18:8080/Servlet/index.jsp?hello=hello") .openConnection(); uc.setConnectTimeout(CONNECT_TIME_OUT); uc.setReadTimeout(READ_TIME_OUT); BufferedReader br = new BufferedReader( new InputStreamReader(uc.getInputStream())); String temp = null; while ((temp = br.readLine()) != null) { sb.append(temp); } mHandler.sendEmptyMessage(VALIDATE_MSG);
2. URLConnection:使用POST请求服务端。
uc = new URL( "http://172.16.10.18:8080/Servlet/index.jsp") .openConnection(); uc.setDoOutput(true); uc.setDoInput(true); OutputStream os = uc.getOutputStream(); os.write("hello=hello".getBytes()); os.flush(); byte[] data = new byte[1024]; InputStream is = uc.getInputStream(); int len = 0; while ((len = is.read(data)) != -1) { sb.append(new String(data, 0, len)); } mHandler.sendEmptyMessage(VALIDATE_MSG);
使用post请求的时候注意两点,uc.setDoOutput(true)这一句,使我们可以向输出流中写入数据,通常是参数。我们使用post请求的一个大致过程是首先进入这个jsp界面,然后拿到这个jsp界面的输出流,我们向这个jsp界面进行数据的写入,然后jsp处理你写入的参数进行页面的显示。os.write之后要flush刷新缓存进行刷新输出流,提交参数。多个参数之间使用&连接。
3.HttpClient 使用GET方法请求服务端。
HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet( "http://172.16.10.18:8080/Servlet/index.jsp?hello=hello"); HttpResponse response = client.execute(get); sb.append(EntityUtils.toString( response.getEntity(), "UTF-8")); mHandler.sendEmptyMessage(VALIDATE_MSG);
这个方法就简单多了,把方法都封装进去了,我们只需要进行地址参数的传入就行了,连输的读取也是一个方法就搞定。
4.HttpClient 使用POST方法请求服务端。
HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost( "http://172.16.10.18:8080/Servlet/index.jsp"); List<BasicNameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("hello", "hello")); UrlEncodedFormEntity uefe = new UrlEncodedFormEntity( params); post.setEntity(uefe); HttpResponse response = client.execute(post); sb.append(EntityUtils.toString( response.getEntity(), "UTF-8")); mHandler.sendEmptyMessage(VALIDATE_MSG);
同样的重点是POST方法,跟之前的类似,不同之处在于参数的提交,这里是通过post.setEntity传递一个封装好的结构体数据进去作为参数。这个参数的构造使用的是List< ? extends BasicNameValuePair>这种类型的参数进行构造。所以这里我们新建一个List类型的参数并UrlEncodedFormEntity uefe = new UrlEncodedFormEntity(params);这样就完成了参数的提交。
访问网络的方法还有很多,大家如果感兴趣可以去搜一下Volley和okhttp,这两个也是很不错的网络访问框架。
package com.example.android_net_code;import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.URL;import java.net.URLConnection;import java.util.ArrayList;import java.util.List;import org.apache.http.HttpResponse;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;public class MainActivity extends Activity { private static final String SERVER_PATH = "http://172.16.10.18:8080/Servlet/index.jsp"; private static final int CONNECT_TIME_OUT = 15 * 1000; private static final int READ_TIME_OUT = 15 * 1000; private static final int VALIDATE_MSG = 0; private TextView txtContent; private Button btnConnect; private StringBuffer sb = new StringBuffer(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } Handler mHandler = new Handler() { public void handleMessage(android.os.Message msg) { switch (msg.what) { case VALIDATE_MSG: txtContent.setText(new String(sb)); break; default: break; } }; }; private void initView() { txtContent = (TextView) findViewById(R.id.content); btnConnect = (Button) findViewById(R.id.connect); btnConnect.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { new Thread() { public void run() { URLConnection uc; try { // --------------POST METHOD --------------------- HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost( "http://172.16.10.18:8080/Servlet/index.jsp"); List<BasicNameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("hello", "hello")); UrlEncodedFormEntity uefe = new UrlEncodedFormEntity( params); post.setEntity(uefe); HttpResponse response = client.execute(post); sb.append(EntityUtils.toString( response.getEntity(), "UTF-8")); mHandler.sendEmptyMessage(VALIDATE_MSG); } catch (Exception e) { e.printStackTrace(); } } }.start(); } }); } // byte[] data = new byte[1024]; // InputStream is = uc.getInputStream(); // int len = 0; // while ((len = is.read(data)) != -1) { // sb.append(new String(data, 0, len)); // } // BufferedReader br = new BufferedReader( // new InputStreamReader(uc.getInputStream())); // String temp = null; // while ((temp = br.readLine()) != null) { // sb.append(temp); // } // --------------POST METHOD --------------------- // uc = new // URL("http://172.16.10.18:8080/Servlet/index.jsp").openConnection() ; // uc.setDoOutput(true); // uc.setDoInput(true); // OutputStream os = uc.getOutputStream() ; // os.write("hello=hello".getBytes()) ; // os.flush() ; // byte[] data = new byte[1024]; // InputStream is = uc.getInputStream() ; // int len = 0 ; // while( (len = is.read(data)) != -1){ // sb.append(new String(data , 0 , len)); // } // HttpClient client = new DefaultHttpClient() ; // HttpGet get = new // HttpGet("http://172.16.10.18:8080/Servlet/index.jsp?hello=hello") ; // HttpResponse response = client.execute(get); // sb.append(EntityUtils.toString(response.getEntity(),"UTF-8")) ; // // HttpPost post = new // HttpPost("http://172.16.10.18:8080/Servlet/index.jsp"); // List<BasicNameValuePair> params = new ArrayList<>() ; // params.add(new BasicNameValuePair("hello", "hello")) ; // UrlEncodedFormEntity uefe = new UrlEncodedFormEntity(params); // post.setEntity(uefe); // HttpResponse response = client.execute(post); // sb.append(EntityUtils.toString(response.getEntity(), "UTF-8")) ;}
0 0
- Android网络编程之URLConnection和HttpClient访问服务器
- Android网络访问之HttpURLConnection和HttpClient
- Android网络访问之HttpURLConnection和HttpClient
- java网络编程URLConnection和HttpClient(下载图片范例)
- 利用HttpClient URLConnection两个类 访问服务器
- Android网络编程之URLConnection&HttpURLConnection
- Android之使用URLConnection进行网络编程
- android获取URLConnection和HttpClient网络请求响应码
- android获取URLConnection和HttpClient网络请求响应码
- android获取URLConnection和HttpClient网络请求响应码
- android获取URLConnection和HttpClient网络请求响应码
- 网络编程之URL和URLConnection
- android网络之URLconnection
- Android网络编程之httpclient
- Android网络编程之HttpClient
- 通过httpclient和urlconnection下载网络文件
- android httpClient和URLConnection的区别
- android 中HttpClient和URLConnection的区别
- 2.Swift初探-基本语法
- 转载 C++的运算符重载
- C#编译器
- Xcode 7 缺少 *.dylib库的解决方法
- 执行多个用例
- Android网络编程之URLConnection和HttpClient访问服务器
- openmeetings3.0.6 二次改动(无需源码)
- 2015年各国竞争力排名,中国领跑金砖国家
- uboot移植 --添加目标板(转载学习使用)
- cut用法
- 安装git
- test9.9
- 乔布斯遗言
- linux下批量替换文件内容