本實例封裝了一個處理安卓客戶端與服務器端交互的幾個方法,對於中文亂碼問題本實例也找到了解決方案.本例能夠處理的場景以下:html
1.與服務器端交互json數據.java
2.Get方式與服務器端交互數據.android
3.Post方式與服務器端交互數據.web
4.HttpClient方式與服務器端交互數據.apache
5.上傳文件到服務器端.json
6.從服務器端下載文件.
7.從服務器端讀取文本文件.瀏覽器
實例截圖:緩存
![](http://static.javashuo.com/static/loading.gif)
本篇文章將實例代碼完整貼出,但願以本文做爲一個交流的平臺,你們集思廣益封裝出更好的處理類.交流地址: http://blog.csdn.net/lk_blog/article/details/7706348#comments
安全
客戶端的封裝類NetTool.java:服務器
- package com.tgb.lk.demo.util;
-
- import java.io.BufferedReader;
- import java.io.DataOutputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.OutputStream;
- import java.net.HttpURLConnection;
- import java.net.MalformedURLException;
- import java.net.URL;
- import java.net.URLEncoder;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Map;
-
- import org.apache.http.HttpEntity;
- import org.apache.http.HttpResponse;
- import org.apache.http.NameValuePair;
- 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 android.os.Environment;
-
-
-
-
-
-
- public class NetTool {
- private static final int TIMEOUT = 10000;
-
-
-
-
- public static String sendTxt(String urlPath, String txt, String encoding)
- throws Exception {
- byte[] sendData = txt.getBytes();
- URL url = new URL(urlPath);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setRequestMethod("POST");
- conn.setConnectTimeout(TIMEOUT);
-
- conn.setDoOutput(true);
- conn.setRequestProperty("Content-Type", "text/xml");
- conn.setRequestProperty("Charset", encoding);
- conn.setRequestProperty("Content-Length", String
- .valueOf(sendData.length));
- OutputStream outStream = conn.getOutputStream();
- outStream.write(sendData);
- outStream.flush();
- outStream.close();
- if (conn.getResponseCode() == 200) {
-
- BufferedReader in = new BufferedReader(new InputStreamReader(conn
- .getInputStream(), encoding));
-
- String retData = null;
- String responseData = "";
- while ((retData = in.readLine()) != null) {
- responseData += retData;
- }
- in.close();
- return responseData;
- }
- return "sendText error!";
- }
-
-
-
-
- public static String sendFile(String urlPath, String filePath,
- String newName) throws Exception {
- String end = "\r\n";
- String twoHyphens = "--";
- String boundary = "*****";
-
- URL url = new URL(urlPath);
- HttpURLConnection con = (HttpURLConnection) url.openConnection();
-
- con.setDoInput(true);
- con.setDoOutput(true);
- con.setUseCaches(false);
-
- con.setRequestMethod("POST");
-
-
- con.setRequestProperty("Connection", "Keep-Alive");
- con.setRequestProperty("Charset", "UTF-8");
- con.setRequestProperty("Content-Type", "multipart/form-data;boundary="
- + boundary);
-
- DataOutputStream ds = new DataOutputStream(con.getOutputStream());
- ds.writeBytes(twoHyphens + boundary + end);
- ds.writeBytes("Content-Disposition: form-data; "
- + "name=\"file1\";filename=\"" + newName + "\"" + end);
- ds.writeBytes(end);
-
-
- FileInputStream fStream = new FileInputStream(filePath);
-
- int bufferSize = 1024;
- byte[] buffer = new byte[bufferSize];
-
- int length = -1;
-
- while ((length = fStream.read(buffer)) != -1) {
-
- ds.write(buffer, 0, length);
- }
- ds.writeBytes(end);
- ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
-
-
- fStream.close();
- ds.flush();
-
-
- InputStream is = con.getInputStream();
- int ch;
- StringBuffer b = new StringBuffer();
- while ((ch = is.read()) != -1) {
- b.append((char) ch);
- }
-
- ds.close();
- return b.toString();
- }
-
-
-
-
- public static String sendGetRequest(String urlPath,
- Map<String, String> params, String encoding) throws Exception {
-
-
- StringBuilder sb = new StringBuilder(urlPath);
- sb.append('?');
-
-
- for (Map.Entry<String, String> entry : params.entrySet()) {
- sb.append(entry.getKey()).append('=').append(
- URLEncoder.encode(entry.getValue(), encoding)).append('&');
- }
- sb.deleteCharAt(sb.length() - 1);
-
- URL url = new URL(sb.toString());
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setRequestMethod("GET");
- conn.setRequestProperty("Content-Type", "text/xml");
- conn.setRequestProperty("Charset", encoding);
- conn.setConnectTimeout(TIMEOUT);
-
- if (conn.getResponseCode() == 200) {
-
- BufferedReader in = new BufferedReader(new InputStreamReader(conn
- .getInputStream(), encoding));
-
- String retData = null;
- String responseData = "";
- while ((retData = in.readLine()) != null) {
- responseData += retData;
- }
- in.close();
- return responseData;
- }
- return "sendGetRequest error!";
-
- }
-
-
-
-
- public static String sendPostRequest(String urlPath,
- Map<String, String> params, String encoding) throws Exception {
- StringBuilder sb = new StringBuilder();
-
- if (params != null && !params.isEmpty()) {
- for (Map.Entry<String, String> entry : params.entrySet()) {
-
- sb.append(entry.getKey()).append('=').append(
- URLEncoder.encode(entry.getValue(), encoding)).append(
- '&');
- }
- sb.deleteCharAt(sb.length() - 1);
- }
-
- byte[] entitydata = sb.toString().getBytes();
- URL url = new URL(urlPath);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setRequestMethod("POST");
- conn.setConnectTimeout(TIMEOUT);
-
- conn.setDoOutput(true);
-
- conn.setRequestProperty("Content-Type",
- "application/x-www-form-urlencoded");
-
- conn.setRequestProperty("Charset", encoding);
- conn.setRequestProperty("Content-Length", String
- .valueOf(entitydata.length));
- OutputStream outStream = conn.getOutputStream();
-
- outStream.write(entitydata);
-
- outStream.flush();
- outStream.close();
-
- if (conn.getResponseCode() == 200) {
-
- BufferedReader in = new BufferedReader(new InputStreamReader(conn
- .getInputStream(), encoding));
-
- String retData = null;
- String responseData = "";
- while ((retData = in.readLine()) != null) {
- responseData += retData;
- }
- in.close();
- return responseData;
- }
- return "sendText error!";
- }
-
-
-
-
- public static String sendHttpClientPost(String urlPath,
- Map<String, String> params, String encoding) throws Exception {
-
- List<NameValuePair> paramPairs = new ArrayList<NameValuePair>();
- if (params != null && !params.isEmpty()) {
- for (Map.Entry<String, String> entry : params.entrySet()) {
- paramPairs.add(new BasicNameValuePair(entry.getKey(), entry
- .getValue()));
- }
- }
-
- UrlEncodedFormEntity entitydata = new UrlEncodedFormEntity(paramPairs,
- encoding);
-
- HttpPost post = new HttpPost(urlPath);
-
- post.setEntity(entitydata);
-
- DefaultHttpClient client = new DefaultHttpClient();
-
- HttpResponse response = client.execute(post);
-
- if (response.getStatusLine().getStatusCode() == 200) {
- HttpEntity entity = response.getEntity();
- InputStream inputStream = entity.getContent();
- InputStreamReader inputStreamReader = new InputStreamReader(
- inputStream, encoding);
- BufferedReader reader = new BufferedReader(inputStreamReader);
- String s;
- String responseData = "";
- while (((s = reader.readLine()) != null)) {
- responseData += s;
- }
- reader.close();
- return responseData;
- }
- return "sendHttpClientPost error!";
- }
-
-
-
-
- public static String readTxtFile(String urlStr, String encoding)
- throws Exception {
- StringBuffer sb = new StringBuffer();
- String line = null;
- BufferedReader buffer = null;
- try {
-
- URL url = new URL(urlStr);
-
- HttpURLConnection urlConn = (HttpURLConnection) url
- .openConnection();
-
- buffer = new BufferedReader(new InputStreamReader(urlConn
- .getInputStream(), encoding));
- while ((line = buffer.readLine()) != null) {
- sb.append(line);
- }
- } catch (Exception e) {
- throw e;
- } finally {
- try {
- buffer.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- return sb.toString();
- }
-
-
-
-
- public static int downloadFile(String urlStr, String path, String fileName)
- throws Exception {
- InputStream inputStream = null;
- try {
- inputStream = getInputStreamFromUrl(urlStr);
- File resultFile = write2SDFromInput(path, fileName, inputStream);
- if (resultFile == null) {
- return -1;
- }
-
- } catch (Exception e) {
- return -1;
- } finally {
- try {
- inputStream.close();
- } catch (Exception e) {
- throw e;
- }
- }
- return 0;
- }
-
-
-
-
-
-
-
-
-
- public static InputStream getInputStreamFromUrl(String urlStr)
- throws MalformedURLException, IOException {
- URL url = new URL(urlStr);
- HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
- InputStream inputStream = urlConn.getInputStream();
- return inputStream;
- }
-
-
-
-
- private static File write2SDFromInput(String directory, String fileName,
- InputStream input) {
- File file = null;
- String SDPATH = Environment.getExternalStorageDirectory().toString();
- FileOutputStream output = null;
- File dir = new File(SDPATH + directory);
- if (!dir.exists()) {
- dir.mkdir();
- }
- try {
- file = new File(dir + File.separator + fileName);
- file.createNewFile();
- output = new FileOutputStream(file);
- byte buffer[] = new byte[1024];
- while ((input.read(buffer)) != -1) {
- output.write(buffer);
- }
- output.flush();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- output.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return file;
- }
- }
客戶端main.xml:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
-
- <TextView
- android:id="@+id/tvData"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="數據" />
-
- <Button
- android:id="@+id/btnTxt"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="與服務器端交互Json數據" />
-
- <Button
- android:id="@+id/btnGet"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="Get方式與服務器端交互數據" />
-
- <Button
- android:id="@+id/btnPost"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="Post方式與服務器端交互數據" />
-
- <Button
- android:id="@+id/btnHttpClient"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="HttpClient方式與服務器端交互數據" />
-
- <Button
- android:id="@+id/btnUploadFile"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="上傳文件到服務器端" />
-
- <Button
- android:id="@+id/btnDownloadFile"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="從服務器端下載文件" />
-
- <Button
- android:id="@+id/btnReadTxtFile"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="從服務器端讀取文本文件" />
-
- </LinearLayout>
客戶端AppClientActivity.java:
- package com.tgb.lk.demo.appclient;
-
- import java.util.HashMap;
- import java.util.Map;
-
- import com.google.gson.Gson;
- import com.tgb.lk.demo.model.Student;
- import com.tgb.lk.demo.util.NetTool;
-
- import android.app.Activity;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.TextView;
-
- public class AppClientActivity extends Activity {
- private TextView tvData = null;
- private Button btnTxt = null;
- private Button btnGet = null;
- private Button btnPost = null;
- private Button btnHttpClient = null;
- private Button btnUploadFile = null;
- private Button btnReadTxtFile = null;
- private Button btnDownloadFile = null;
-
-
- private String txtUrl = "http://192.168.1.46:8080/AppServer/SynTxtDataServlet";
- private String url = "http://192.168.1.46:8080/AppServer/SynDataServlet";
- private String uploadUrl = "http://192.168.1.46:8080/AppServer/UploadFileServlet";
- private String fileUrl = "http://192.168.1.46:8080/AppServer/file.jpg";
- private String txtFileUrl = "http://192.168.1.46:8080/AppServer/txtFile.txt";
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
- tvData = (TextView) findViewById(R.id.tvData);
- btnTxt = (Button) findViewById(R.id.btnTxt);
- btnGet = (Button) findViewById(R.id.btnGet);
- btnPost = (Button) findViewById(R.id.btnPost);
- btnHttpClient = (Button) findViewById(R.id.btnHttpClient);
- btnUploadFile = (Button) findViewById(R.id.btnUploadFile);
- btnReadTxtFile = (Button) findViewById(R.id.btnReadTxtFile);
- btnDownloadFile = (Button) findViewById(R.id.btnDownloadFile);
-
- btnTxt.setOnClickListener(btnListener);
- btnGet.setOnClickListener(btnListener);
- btnPost.setOnClickListener(btnListener);
- btnHttpClient.setOnClickListener(btnListener);
- btnUploadFile.setOnClickListener(btnListener);
- btnReadTxtFile.setOnClickListener(btnListener);
- btnDownloadFile.setOnClickListener(btnListener);
-
- }
-
- OnClickListener btnListener = new OnClickListener() {
- String retStr = "";
-
- @Override
- public void onClick(View v) {
- switch (v.getId()) {
- case R.id.btnTxt:
- Student student = new Student();
- student.setId(1);
- student.setName("李坤");
- student.setClasses("五期信息技術提升班");
- Gson gson = new Gson();
- String jsonTxt = gson.toJson(student);
- try {
- retStr = NetTool.sendTxt(txtUrl, jsonTxt,"UTF-8");
- } catch (Exception e2) {
- e2.printStackTrace();
- }
- break;
- case R.id.btnGet:
- Map<String, String> map = new HashMap<String, String>();
- map.put("name", "李坤");
- map.put("age", "26");
- map.put("classes", "五期信息技術提升班");
- try {
- retStr = NetTool.sendGetRequest(url, map, "utf-8");
- } catch (Exception e) {
- e.printStackTrace();
- }
- break;
- case R.id.btnPost:
- Map<String, String> map2 = new HashMap<String, String>();
- map2.put("name", "李坤");
- map2.put("age", "26");
- map2.put("classes", "五期信息技術提升班");
- try {
- retStr = NetTool.sendPostRequest(url, map2, "utf-8");
- } catch (Exception e) {
- e.printStackTrace();
- }
- break;
- case R.id.btnHttpClient:
- Map<String, String> map3 = new HashMap<String, String>();
- map3.put("name", "李坤");
- map3.put("age", "26");
- map3.put("classes", "五期信息技術提升班");
- try {
- retStr = NetTool.sendHttpClientPost(url, map3, "utf-8");
- } catch (Exception e) {
- e.printStackTrace();
- }
- break;
- case R.id.btnUploadFile:
-
- try {
- retStr = NetTool.sendFile(uploadUrl, "/sdcard/image.jpg",
- "image1.jpg");
- } catch (Exception e) {
- e.printStackTrace();
- }
- break;
- case R.id.btnReadTxtFile:
- try {
-
- retStr = NetTool.readTxtFile(txtFileUrl, "UTF-8");
- } catch (Exception e1) {
- e1.printStackTrace();
- }
- break;
- case R.id.btnDownloadFile:
- try {
- NetTool.downloadFile(fileUrl, "/download", "newfile.jpg");
- } catch (Exception e) {
- e.printStackTrace();
- }
- break;
- default:
- break;
- }
- tvData.setText(retStr);
- }
- };
- }
客戶端Student.java
- package com.tgb.lk.demo.model;
-
- public class Student {
- private int id;
- private String name;
- private String classes;
-
- public int getId() {
- return id;
- }
-
- public void setId(int id) {
- this.id = id;
- }
-
-
-
- @Override
- public String toString() {
- return "Student [classes=" + classes + ", id=" + id + ", name=" + name
- + "]";
- }
- }
客戶端AndroidManifest.xml:
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.tgb.lk.demo.appclient"
- android:versionCode="1"
- android:versionName="1.0" >