android客户端通过Get方式提交参数给服务器,使用URL和HttpURLConnection实现,以及乱码问题解决

来源:互联网 发布:mac电脑淘宝秒杀软件 编辑:程序博客网 时间:2024/06/05 18:58

                                        服务器端的设置

服务器端采用Struts2来接收Android端的请求,android版本为2.2.3配置如下:

1:web.xml的配置为

[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  
  3.   
  4.     <display-name>Struts Blank</display-name>  
  5.   
  6.     <filter>  
  7.         <filter-name>struts2</filter-name>  
  8.         <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>  
  9.     </filter>  
  10.   
  11.     <filter-mapping>  
  12.         <filter-name>struts2</filter-name>  
  13.         <url-pattern>/*</url-pattern>  
  14.     </filter-mapping>  
  15.   
  16.     <welcome-file-list>  
  17.         <welcome-file>index.html</welcome-file>  
  18.     </welcome-file-list>  
  19.   
  20. </web-app>  


2:VideoManageAction类

[java] view plain copy
  1. package com.capinfotech.android;  
  2.   
  3. import javax.servlet.http.HttpServletRequest;  
  4. import javax.servlet.http.HttpServletResponse;  
  5.   
  6. import org.apache.struts2.interceptor.ServletRequestAware;  
  7. import org.apache.struts2.interceptor.ServletResponseAware;  
  8.   
  9. import com.opensymphony.xwork2.ActionSupport;  
  10.   
  11. public class VideoManageAction extends ActionSupport implements ServletRequestAware, ServletResponseAware {  
  12.   
  13.     private HttpServletRequest request;  
  14.     private HttpServletResponse response;  
  15.       
  16.     public void setServletRequest(HttpServletRequest request) {  
  17.         this.request = request;  
  18.     }  
  19.   
  20.     public void setServletResponse(HttpServletResponse response) {  
  21.         this.response = response;  
  22.     }  
  23.       
  24.     public void save() {  
  25.         String method = this.request.getMethod();  //获得requst的方法  
  26.         String  title = null;  
  27.         Integer timelength = null;  
  28.         if("GET".equals(method)) {  
  29.             title = request.getParameter("title");  //获得参数title的值  
  30.             timelength = new Integer(request.getParameter("timelength"));  //获得参数timelength的值  
  31.             System.out.println("title: " + title);     //输出title的值  
  32.             System.out.println("timelength: " + timelength.intValue());    //输出timelength的值  
  33.               
  34.         } else {  
  35.             title = request.getParameter("title");  
  36.             timelength = new Integer(request.getParameter("timelength"));  
  37.             System.out.println("title: " + title);  
  38.             System.out.println("timelength: " + timelength.intValue());  
  39.         }   
  40.     }  
  41. }  


3:struts.xml的配置为

[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE struts PUBLIC  
  3.         "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
  4.         "http://struts.apache.org/dtds/struts-2.0.dtd">  
  5.   
  6. <struts>  
  7.   
  8.    <package name="android" namespace="/android" extends="struts-default">  
  9.        
  10.        <action name="upload" class="com.capinfotech.android.VideoManageAction" method="save" >  
  11.               
  12.        </action>  
  13.          
  14.     </package>  
  15. </struts>  


                                                                                             android端的配置

1:androidmanifest.xml的内容

[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.       package="com.capinfotech.upload"  
  4.       android:versionCode="1"  
  5.       android:versionName="1.0">  
  6.     <application android:icon="@drawable/icon" android:label="@string/app_name">  
  7.      <uses-library android:name="android.test.runner" />    
  8.         <activity android:name=".MainActivity"  
  9.                   android:label="@string/app_name">  
  10.             <intent-filter>  
  11.                 <action android:name="android.intent.action.MAIN" />  
  12.                 <category android:name="android.intent.category.LAUNCHER" />  
  13.             </intent-filter>  
  14.         </activity>  
  15.   
  16.     </application>  
  17.     <uses-sdk android:minSdkVersion="8" />  
  18.      <uses-permission android:name="android.permission.INTERNET" />  
  19.      <instrumentation android:name="android.test.InstrumentationTestRunner"    
  20.      android:targetPackage="com.capinfotech.upload" android:label="Tests for My App" />  
  21. </manifest>   


2:HttpRequest类的内容

[html] view plain copy
  1. package com.capinfotech.net;  
  2.   
  3. import java.io.IOException;  
  4. import java.net.HttpURLConnection;  
  5. import java.net.MalformedURLException;  
  6. import java.net.URL;  
  7. import java.util.Map;  
  8.   
  9. import android.util.Log;  
  10.   
  11. public class HttpRequest {  
  12.     private static final String TAG = "HttpRequest";  
  13.     public static boolean sendGetRequest(String path, Map<String, String> params) throws IOException {  
  14.         /*  
  15.          * http://127.0.0.1/AndroidService/android/upload?title=aaa&timelength=90的形式  
  16.          */  
  17.         StringBuilder sb = new StringBuilder(path);  
  18.         sb.append('?');  
  19.         for(Map.Entry<String, String> entry : params.entrySet()) {  
  20.             sb.append(entry.getKey()).append('=').append(entry.getValue()).append('&');  
  21.         }  
  22.         sb.deleteCharAt(sb.length()-1);  
  23.           
  24.         try {  
  25.             URL url = new URL(sb.toString());  
  26.             HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
  27.             conn.setRequestMethod("GET");    //设置方法为GET  
  28.             conn.setReadTimeout(5 * 1000);   //设置过期时间为5秒  
  29.             if(conn.getResponseCode() == 200) {  //如果成功返回  
  30.                 return true;  
  31.             }   
  32.         } catch (MalformedURLException e) {  
  33.             e.printStackTrace();  
  34.               
  35.             Log.e(TAG, e.toString());  
  36.             return false;  
  37.         }  
  38.         return false;  
  39.     }  
  40. }  


3:HttpRequestTest类

[java] view plain copy
  1. package com.capinfotech.test;  
  2.   
  3. import java.io.IOException;  
  4. import java.util.HashMap;  
  5. import java.util.Map;  
  6.   
  7. import android.test.AndroidTestCase;  
  8. import android.util.Log;  
  9.   
  10. import com.capinfotech.net.HttpRequest;  
  11.   
  12. public class HttpRequestTest extends AndroidTestCase {  
  13.     private static final String TAG = "HttpRequestTest";  
  14.   
  15.     public void testSendGetRequest() throws IOException {  
  16.         Map<String, String> params = new HashMap<String, String>();  
  17.         params.put("title""long");  
  18.         params.put("timelength""80");  
  19.           
  20.         String path = "http://192.168.1.105/AndroidService/android/upload";  
  21.         if(HttpRequest.sendGetRequest(path, params)) {  
  22.             Log.i(TAG, "success");  
  23.         } else {  
  24.             Log.i(TAG, "failure");  
  25.         }  
  26.     }  
  27. }  


4:测试结果页面

上传的参数中含有中文时

改变方法testSendGetRequest()方法里的几行程序:

[java] view plain copy
  1. Map<String, String> params = new HashMap<String, String>();  
  2.         params.put("title""变形金刚3");  
  3.         params.put("timelength""80");  


测试结果页面为:

需要修改的程序:

1:HttpRequest类修改为:

[java] view plain copy
  1. package com.capinfotech.net;  
  2.   
  3. import java.io.IOException;  
  4. import java.net.HttpURLConnection;  
  5. import java.net.MalformedURLException;  
  6. import java.net.URL;  
  7. import java.net.URLEncoder;  
  8. import java.util.Map;  
  9.   
  10. import android.util.Log;  
  11.   
  12. public class HttpRequest {  
  13.     private static final String TAG = "HttpRequest";  
  14.     public static boolean sendGetRequest(String path, Map<String, String> params, String enc) throws IOException {  
  15.           
  16.         /* 
  17.          * http://127.0.0.1/AndroidService/android/upload?title=aaa&timelength=90的形式 
  18.          */  
  19.         StringBuilder sb = new StringBuilder(path);  
  20.         sb.append('?');  
  21.         for(Map.Entry<String, String> entry : params.entrySet()) {  
  22.             sb.append(entry.getKey()).append('=').append(URLEncoder.encode(entry.getValue(), enc)).append('&');    
  23.         }  
  24.         sb.deleteCharAt(sb.length()-1);  
  25.           
  26.         try {  
  27.             URL url = new URL(sb.toString());  
  28.             HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
  29.             conn.setRequestMethod("GET");    //设置方法为GET  
  30.             conn.setReadTimeout(5 * 1000);   //设置过期时间为5秒  
  31.             if(conn.getResponseCode() == 200) {  //如果成功返回  
  32.                 return true;  
  33.             }   
  34.         } catch (MalformedURLException e) {  
  35.             e.printStackTrace();  
  36.               
  37.             Log.e(TAG, e.toString());  
  38.             return false;  
  39.         }  
  40.         return false;  
  41.     }  
  42. }  


主要是在函数中添加了一个表示编码的参数enc,用来控制编码的格式问题

2:HttpRequest类修改为

[java] view plain copy
  1. public class HttpRequestTest extends AndroidTestCase {  
  2.     private static final String TAG = "HttpRequestTest";  
  3.   
  4.     public void testSendGetRequest() throws IOException {  
  5.         Map<String, String> params = new HashMap<String, String>();  
  6.         params.put("title""变形金刚3");  
  7.         params.put("timelength""80");  
  8.           
  9.         String path = "http://192.168.1.105/AndroidService/android/upload";  
  10.         if(HttpRequest.sendGetRequest(path, params, "UTF-8")) {  
  11.             Log.i(TAG, "success");  
  12.         } else {  
  13.             Log.i(TAG, "failure");  
  14.         }  
  15.     }  
  16. }  


3:测试结果:

这时发现在tomcat控制台输出的参数还是乱码的,之后的工作就是修改服务器的程序

4:VideoManageAction类的内容改为

[java] view plain copy
  1. package com.capinfotech.android;  
  2.   
  3. import java.io.UnsupportedEncodingException;  
  4.   
  5. import javax.servlet.http.HttpServletRequest;  
  6. import javax.servlet.http.HttpServletResponse;  
  7.   
  8. import org.apache.struts2.interceptor.ServletRequestAware;  
  9. import org.apache.struts2.interceptor.ServletResponseAware;  
  10.   
  11. import com.opensymphony.xwork2.ActionSupport;  
  12.   
  13. public class VideoManageAction extends ActionSupport implements ServletRequestAware, ServletResponseAware {  
  14.   
  15.     private HttpServletRequest request;  
  16.     private HttpServletResponse response;  
  17.       
  18.     public void setServletRequest(HttpServletRequest request) {  
  19.         this.request = request;  
  20.     }  
  21.   
  22.     public void setServletResponse(HttpServletResponse response) {  
  23.         this.response = response;  
  24.     }  
  25.       
  26.     public void save() {  
  27.         String method = this.request.getMethod();  //获得requst的方法  
  28.         String  title = null;  
  29.         Integer timelength = null;  
  30.         try {  
  31.         if("GET".equals(method)) {  
  32.                 byte[] titleByte = request.getParameter("title").getBytes("iso-8859-1");  //获得title参数对应的二进制数据  
  33.                 title = new String(titleByte, "UTF-8");  
  34.                 timelength = new Integer(request.getParameter("timelength"));  //获得参数timelength的值  
  35.                 System.out.println("title: " + title);     //输出title的值  
  36.                 System.out.println("timelength: " + timelength.intValue());    //输出timelength的值  
  37.             } else {  
  38.                 title = request.getParameter("title");  
  39.                 timelength = new Integer(request.getParameter("timelength"));  
  40.                 System.out.println("title: " + title);  
  41.                 System.out.println("timelength: " + timelength.intValue());  
  42.             }   
  43.         } catch (UnsupportedEncodingException e) {  
  44.                 e.printStackTrace();  
  45.             }    
  46.     }  
  47.       
  48. }  


5:测试结果

 

6:乱码问题总结造成中文乱码的原因有两个:首先,并没有对URL发送的参数进行编码,然后就是服务器端接受参数的问题,Tomcat服务器接收参数时默认为ISO-8859-1,这个编码并不包含中文的编码

 

                                                                                                       android端的程序

1:strings.xml里的内容,定义用到的字符串资源

[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <string name="hello">Hello World, MainActivity!</string>  
  4.     <string name="app_name">上传数据到服务器</string>  
  5.     <string name="title">视频名称</string>  
  6.     <string name="timelength">时长</string>  
  7.     <string name="button">保存</string>  
  8.     <string name="success">保存成功</string>  
  9.     <string name="error">保存失败</string>  
  10. </resources>  

2:main.xml的内容,定义布局文件

[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent"  
  6.     >  
  7. <TextView    
  8.     android:layout_width="fill_parent"   
  9.     android:layout_height="wrap_content"   
  10.     android:text="@string/title"  
  11.     />  
  12. <EditText  
  13.     android:layout_width="fill_parent"   
  14.     android:layout_height="wrap_content"   
  15.     android:id="@+id/title"  
  16.     />  
  17.   
  18. <TextView    
  19.     android:layout_width="fill_parent"   
  20.     android:layout_height="wrap_content"   
  21.     android:text="@string/timelength"  
  22.     />  
  23. <EditText  
  24.     android:layout_width="fill_parent"   
  25.     android:layout_height="wrap_content"   
  26.     android:id="@+id/timelength"  
  27.     />  
  28. <Button  
  29.     android:layout_width="wrap_content"   
  30.     android:layout_height="wrap_content"   
  31.     android:id="@+id/button"  
  32.     android:text="@string/button"  
  33. />  
  34. </LinearLayout>  


3:MainActivity的内容

[java] view plain copy
  1. package com.capinfotech.upload;  
  2.   
  3. import java.io.IOException;  
  4. import java.util.HashMap;  
  5. import java.util.Map;  
  6.   
  7. import com.capinfotech.net.HttpRequest;  
  8.   
  9. import android.app.Activity;  
  10. import android.os.Bundle;  
  11. import android.util.Log;  
  12. import android.view.View;  
  13. import android.widget.Button;  
  14. import android.widget.EditText;  
  15. import android.widget.Toast;  
  16.   
  17. public class MainActivity extends Activity {  
  18.     private static final String TAG = "MainActivity";  
  19.       
  20.     private EditText titleEditText = null;  
  21.     private EditText timeEditText = null;  
  22.     private Button button = null;  
  23.       
  24.     @Override  
  25.     public void onCreate(Bundle savedInstanceState) {  
  26.         super.onCreate(savedInstanceState);  
  27.         setContentView(R.layout.main);  
  28.           
  29.         titleEditText = (EditText)findViewById(R.id.title);  
  30.         timeEditText = (EditText)findViewById(R.id.timelength);  
  31.         button = (Button)findViewById(R.id.button);  
  32.           
  33.         button.setOnClickListener(new View.OnClickListener() {  
  34.               
  35.             @Override  
  36.             public void onClick(View v) {  
  37.                 Map<String, String> params = new HashMap<String, String>();  
  38.                 params.put("title", titleEditText.getText().toString());   //获取输入的视频的名字  
  39.                 params.put("timelength", timeEditText.getText().toString());   //获取输入的视频的时长  
  40.                   
  41.                 String path = "http://192.168.1.105/AndroidService/android/upload";  //路径  
  42.                 try {  
  43.                     if(HttpRequest.sendGetRequest(path, params, "UTF-8")) {  
  44.                         Log.i(TAG, "success");  
  45.                         Toast.makeText(MainActivity.this, R.string.success, Toast.LENGTH_LONG).show(); //提示保存成功  
  46.                     } else {  
  47.                         Log.i(TAG, "failure");  
  48.                         Toast.makeText(MainActivity.this, R.string.error, Toast.LENGTH_LONG).show(); //提示保存失败  
  49.                     }  
  50.                 } catch (IOException e) {  
  51.                     Log.i(TAG, "failure");  
  52.                     Toast.makeText(MainActivity.this, R.string.error, Toast.LENGTH_LONG).show();  
  53.                 }  
  54.             }  
  55.         });  
  56.     }  
  57. }  


4:程序界面与运行效果

0 0