当前位置:文档之家› Android连接服务器方法

Android连接服务器方法

由于刚接触android开发,故此想把学到的基础知识记录一下,以备查询,故此写的比较啰嗦:步骤如下:一、介绍:此文主要是介利用android网络通信功能把android客户端的数据传给web服务端进行操作此项目列举三个个传值方式:1、GET方式,2、POST方式,3、HttpClient 方式二、新建一个android工程——NewsManage工程目录:三、AndroidManifest.xml配置清单由于要访问网络,故需要添加网络访问权限,红色标注添加部分<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="/apk/res/android" package="com.example.newsmanage"android:versionCode="1"android:versionName="1.0" ><uses-sdk android:minSdkVersion="8" /><uses-permission android:name="android.permission.INTERNET"/><applicationandroid:icon="@drawable/ic_launcher"android:label="@string/app_name" ><activityandroid:name=".NewsManageActivity"android:label="@string/app_name" ><intent-filter><action android:name="android.intent.action.MAIN" /><categoryandroid:name="UNCHER" /></intent-filter></activity></application></manifest>四、main.xml配置:<?xml version="1.0" encoding="utf-8"?><LinearLayoutxmlns:android="/apk/res/android"android:layout_width="fill_parent"android:layout_height="fill_parent"android:orientation="vertical" ><TextViewandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:text="@string/title" /><EditTextandroid:id="@+id/title"android:layout_width="match_parent"android:layout_height="wrap_content" ><requestFocus /></EditText><TextViewandroid:id="@+id/textView1"android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="@string/timelength" /><EditTextandroid:id="@+id/timelength"android:layout_width="match_parent"android:layout_height="wrap_content"android:numeric="integer"/><Buttonandroid:id="@+id/button"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="@string/button" android:onClick="save"/></LinearLayout>五、string.xml配置:<?xml version="1.0" encoding="utf-8"?><resources><string name="hello">Hello World, NewsManageActivity!</string> <string name="app_name">资讯管理</string><string name="title">视频标题</string><string name="timelength">播放时长</string><string name="button">保存</string><string name="success">保存成功</string><string name="fail">保存失败</string></resources>六、NewsManageActivity.java Activity源码:package com.example.newsmanage;import com.example.service.NewsService;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;public class NewsManageActivity extends Activity {/** Called when the activity is first created. */EditText titleText;EditText lengthText;Button button;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.main);titleText = (EditText) this.findViewById(R.id.title);lengthText = (EditText) this.findViewById(R.id.timelength); button = (Button) this.findViewById(R.id.button);}public void save(View v) throws Exception{String title = titleText.getText().toString();String timelength = lengthText.getText().toString();boolean result = NewsService.save(title,timelength);if(result){Toast.makeText(getApplicationContext(),R.string.success, Toast.LENGTH_LONG).show();} else {Toast.makeText(getApplicationContext(),R.string.fail,Toast.LENGTH_LONG).show();}}}七、NewsService .java 业务类源码:注:业务类提供三种发送请求的方式:get/post/httpClientpackage com.example.service;import java.io.OutputStream;import .HttpURLConnection;import .URL;import .URLEncoder;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import org.apache.http.HttpResponse;import ValuePair;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;public class NewsService {/*** 保存数据,传递参数给web服务器端* @param title 标题* @param timelength 时长* @return*/public static boolean save(String title, String timelength) throws Exception {//119.119.228.105为本机IP地址,不能用localhost代替String path = "http://119.119.228.105:8080/web/ManageServlet";Map<String,String> params = new HashMap<String,String>();params.put("title", title);params.put("timelength", timelength);//get请求方式//return sendGETRequest(path,params,"UTF-8");//post请求方式//return sendPOSTRequest(path,params,"UTF-8");//httpClient请求方式,如果单纯传递参数的话建议使用GET或者POST请求方式return sendHttpClientPOSTRequest(path,params,"UTF-8");//httpclient 已经集成在android中}/*** 通过HttpClient发送post请求* @param path* @param params* @param encoding* @return* @throws Exception*/private static boolean sendHttpClientPOSTRequest(String path,Map<String, String> params, String encoding) throws Exception {List<NameValuePair> pairs = new ArrayList<NameValuePair>();//存放请求参数for(Map.Entry<String, String> entry:params.entrySet()){pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); }//防止客户端传递过去的参数发生乱码,需要对此重新编码成UTF-8UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs,encoding);HttpPost httpPost = new HttpPost(path);httpPost.setEntity(entity);DefaultHttpClient client = new DefaultHttpClient();HttpResponse response = client.execute(httpPost);if(response.getStatusLine().getStatusCode() == 200){return true;}return false;}/*** 发送post请求* @param path 请求路径* @param params 请求参数* @param encoding 编码* @return 请求是否成功*/private static boolean sendPOSTRequest(String path,Map<String, String> params, String encoding) throws Exception{StringBuilder data = new StringBuilder(path);for(Map.Entry<String, String> entry:params.entrySet()){data.append(entry.getKey()).append("=");//防止客户端传递过去的参数发生乱码,需要对此重新编码成UTF-8data.append(URLEncoder.encode(entry.getValue(),encoding));data.append("&");}data.deleteCharAt(data.length() - 1);byte[] entity = data.toString().getBytes();//得到实体数据HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();conn.setConnectTimeout(5000);conn.setRequestMethod("POST");conn.setDoOutput(true);//设置为允许对外输出数据conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");conn.setRequestProperty("Content-Length",String.valueOf(entity.length));OutputStream outStream = conn.getOutputStream();outStream.write(entity);//写到缓存if(conn.getResponseCode()==200){//只有取得服务器返回的http协议的任何一个属性时才能把请求发送出去return true;}return false;}/*** 发送GET请求* @param path 请求路径* @param params 请求参数* @return 请求是否成功* @throws Exception*/private static boolean sendGETRequest(String path,Map<String, String> params,String encoding) throws Exception {StringBuilder url = new StringBuilder(path);url.append("?");for(Map.Entry<String, String> entry:params.entrySet()){url.append(entry.getKey()).append("=");//get方式请求参数时对参数进行utf-8编码,URLEncoder//防止客户端传递过去的参数发生乱码,需要对此重新编码成UTF-8url.append(URLEncoder.encode(entry.getValue(), encoding));url.append("&");}url.deleteCharAt(url.length()-1);HttpURLConnection conn = (HttpURLConnection) new URL(url.toString()).openConnection();conn.setConnectTimeout(5000);conn.setRequestMethod("GET");if(conn.getResponseCode() == 200){return true;}return false;}}八、由于要把数据传递给web服务端,而web端传递过来的数据有两种格式,故需要新建一个web服务,使之能接收android客户端传递的参数;1、新建一个servlet可以接收传递的参数,源码如下:package com.example.servlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/*** Servlet implementation class ManageServlet*/public class ManageServlet extends HttpServlet {private static final long serialVersionUID = 1L;/*** @see HttpServlet#HttpServlet()*/public ManageServlet() {super();}/*** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)*/protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String title = request.getParameter("title");//把客户端传递过来的参数进行重新编码使之能支持中文//title = new String(title.getBytes("ISO8859-1"),"UTF-8");//使用过滤器后就不需要每次都要进行此操作String timelength = request.getParameter("timelength");System.out.println("视频名称:"+title);System.out.println("播放时长:"+timelength);}/*** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)*/protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String title = request.getParameter("title");//把客户端传递过来的参数进行重新编码使之能支持中文//title = new String(title.getBytes("ISO8859-1"),"UTF-8");//使用过滤器后就不需要每次都要进行此操作String timelength = request.getParameter("timelength");System.out.println("视频名称:"+title);System.out.println("播放时长:"+timelength);}}2、由于传递过来的参数默认编码为ISO8895-1,故打印后台的参数回事乱码故需要传递的过来的参数进行编码,但是如果每次都要对传递过来的参数都要进行编码转换,是比较麻烦的,故需要建立一个拦截器,对传递过来的参数进行统一在一起进行编码转换,当请求/*时拦截器先进行编码处理:拦截器代码如下:EncodingFilter .java 源码如下:package com.example.filter;import java.io.IOException;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest;/*** Servlet Filter implementation class EncodingFilter*/public class EncodingFilter implements Filter {/*** Default constructor.*/public EncodingFilter() {}/*** @see Filter#destroy()*/public void destroy() {}/*** @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) */public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {HttpServletRequest req = (HttpServletRequest) request;if("GET".equals(req.getMethod())){EncodingHttpServletRequest wrapper = new EncodingHttpServletRequest(req);chain.doFilter(wrapper, response);} else {//postreq.setCharacterEncoding("UTF-8");chain.doFilter(request, response);}}/*** @see Filter#init(FilterConfig)*/public void init(FilterConfig fConfig) throws ServletException { }}EncodingHttpServletRequest .java源码如下:package com.example.filter;import java.io.UnsupportedEncodingException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletRequestWrapper;public class EncodingHttpServletRequest extends HttpServletRequestWrapper {private HttpServletRequest request;public EncodingHttpServletRequest(HttpServletRequest request) {super(request);this.request = request;}@Overridepublic String getParameter(String name) {String value = request.getParameter(name);if(value!=null){try {value = new String(value.getBytes("ISO8859-1"),"UTF-8");} catch (UnsupportedEncodingException e) {e.printStackTrace();}}return value;}}注意:在运行android项目前必须先运行web服务九、先运行web服务器,然后运行android项目,发送参数后,web后台就可以打印出相应的信息十、注意事项以及相关知识点:1、由于涉及访问网络,故需要添加网络访问权限<uses-permissionandroid:name="android.permission.INTERNET"/>2、访问web服务时地址必须写网络的IP地址,否则会在本地服务上查找3、熟悉怎么向web服务端发送请求以及方式(http协议)GET方式:HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();conn.setConnectTimeout(5000);conn.setRequestMethod("GET");conn.getResponseCode() == 200 来判断是否请求成功POST方式:byte[] entity = data.toString().getBytes();//得到实体数据HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();conn.setConnectTimeout(5000);conn.setRequestMethod("POST");conn.setDoOutput(true);//设置为允许对外输出数据conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");conn.setRequestProperty("Content-Length",String.valueOf(entity.length));OutputStream outStream = conn.getOutputStream();outStream.write(entity);//写到缓存if(conn.getResponseCode()==200){//只有取得服务器返回的http协议的任何一个属性时才能把请求发送出去return true;}HttpClient方式:List<NameValuePair> pairs = new ArrayList<NameValuePair>();//存放请求参数for(Map.Entry<String, String> entry:params.entrySet()){pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));}//防止客户端传递过去的参数发生乱码,需要对此重新编码成UTF-8UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs,encoding);HttpPost httpPost = new HttpPost(path);httpPost.setEntity(entity);DefaultHttpClient client = new DefaultHttpClient();HttpResponse response = client.execute(httpPost);if(response.getStatusLine().getStatusCode() == 200){return true;}4、乱码产生的原因:(1)、通过get方式提交请求参数时,没有对中文进行URL编码(2)、 Tomcat服务器默认采用ISO8895-1编码得到的参数如果乱码表示为--> -->,则说明是由于客户端传递参数没有编码的原因如果乱码表示为,则说明是由于服务器端的默认编码不一致或者不支持中文的原因5、熟悉拦截器的使用以及原理。

相关主题