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

服务器端的设置

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

1:web.xml的配置为

<?xml version="1.0" encoding="UTF-8"?>
<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">

    <display-name>Struts Blank</display-name>

    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>

</web-app>

2:VideoManageAction类

package com.capinfotech.android;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import com.opensymphony.xwork2.ActionSupport;

public class VideoManageAction extends ActionSupport implements ServletRequestAware, ServletResponseAware {

	private HttpServletRequest request;
	private HttpServletResponse response;
	
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}
	
	public void save() {
		String method = this.request.getMethod();  //获得requst的方法
		String  title = null;
		Integer timelength = null;
		if("GET".equals(method)) {
			title = request.getParameter("title");  //获得参数title的值
			timelength = new Integer(request.getParameter("timelength"));  //获得参数timelength的值
			System.out.println("title: " + title);     //输出title的值
			System.out.println("timelength: " + timelength.intValue());    //输出timelength的值
			
		} else {
			title = request.getParameter("title");
			timelength = new Integer(request.getParameter("timelength"));
			System.out.println("title: " + title);
			System.out.println("timelength: " + timelength.intValue());
		} 
	}
}

3:struts.xml的配置为

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

   <package name="android" namespace="/android" extends="struts-default">
   	 
   	   <action name="upload" class="com.capinfotech.android.VideoManageAction" method="save" >
   	        
   	   </action>
   	   
    </package>
</struts>

android端的配置

1:androidmanifest.xml的内容

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.capinfotech.upload"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
     <uses-library android:name="android.test.runner" />  
        <activity android:name=".MainActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
    <uses-sdk android:minSdkVersion="8" />
     <uses-permission android:name="android.permission.INTERNET" />
     <instrumentation android:name="android.test.InstrumentationTestRunner"  
     android:targetPackage="com.capinfotech.upload" android:label="Tests for My App" />
</manifest> 

2:HttpRequest类的内容

package com.capinfotech.net;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;

import android.util.Log;

public class HttpRequest {
	private static final String TAG = "HttpRequest";
	public static boolean sendGetRequest(String path, Map<String, String> params) throws IOException {
		/*
		 * http://127.0.0.1/AndroidService/android/upload?title=aaa&timelength=90的形式
		 */
		StringBuilder sb = new StringBuilder(path);
		sb.append('?');
		for(Map.Entry<String, String> entry : params.entrySet()) {
			sb.append(entry.getKey()).append('=').append(entry.getValue()).append('&');
		}
		sb.deleteCharAt(sb.length()-1);
		
		try {
			URL url = new URL(sb.toString());
			HttpURLConnection conn = (HttpURLConnection)url.openConnection();
			conn.setRequestMethod("GET");    //设置方法为GET
			conn.setReadTimeout(5 * 1000);   //设置过期时间为5秒
			if(conn.getResponseCode() == 200) {  //如果成功返回
				return true;
			} 
		} catch (MalformedURLException e) {
			e.printStackTrace();
			
			Log.e(TAG, e.toString());
			return false;
		}
		return false;
	}
}

3:HttpRequestTest类

package com.capinfotech.test;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import android.test.AndroidTestCase;
import android.util.Log;

import com.capinfotech.net.HttpRequest;

public class HttpRequestTest extends AndroidTestCase {
	private static final String TAG = "HttpRequestTest";

	public void testSendGetRequest() throws IOException {
		Map<String, String> params = new HashMap<String, String>();
		params.put("title", "long");
		params.put("timelength", "80");
		
		String path = "http://192.168.1.105/AndroidService/android/upload";
		if(HttpRequest.sendGetRequest(path, params)) {
			Log.i(TAG, "success");
		} else {
			Log.i(TAG, "failure");
		}
	}
}

4:测试结果页面

上传的参数中含有中文时

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

Map<String, String> params = new HashMap<String, String>();
params.put("title", "变形金刚3");
params.put("timelength", "80");

测试结果页面为:

需要修改的程序:

1:HttpRequest类修改为:

package com.capinfotech.net;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

import android.util.Log;

public class HttpRequest {
	private static final String TAG = "HttpRequest";
	public static boolean sendGetRequest(String path, Map<String, String> params, String enc) throws IOException {
		
		/*
		 * http://127.0.0.1/AndroidService/android/upload?title=aaa&timelength=90的形式
		 */
		StringBuilder sb = new StringBuilder(path);
		sb.append('?');
		for(Map.Entry<String, String> entry : params.entrySet()) {
			sb.append(entry.getKey()).append('=').append(URLEncoder.encode(entry.getValue(), enc)).append('&');  
		}
		sb.deleteCharAt(sb.length()-1);
		
		try {
			URL url = new URL(sb.toString());
			HttpURLConnection conn = (HttpURLConnection)url.openConnection();
			conn.setRequestMethod("GET");    //设置方法为GET
			conn.setReadTimeout(5 * 1000);   //设置过期时间为5秒
			if(conn.getResponseCode() == 200) {  //如果成功返回
				return true;
			} 
		} catch (MalformedURLException e) {
			e.printStackTrace();
			
			Log.e(TAG, e.toString());
			return false;
		}
		return false;
	}
}

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

2:HttpRequest类修改为

public class HttpRequestTest extends AndroidTestCase {
	private static final String TAG = "HttpRequestTest";

	public void testSendGetRequest() throws IOException {
		Map<String, String> params = new HashMap<String, String>();
		params.put("title", "变形金刚3");
		params.put("timelength", "80");
		
		String path = "http://192.168.1.105/AndroidService/android/upload";
		if(HttpRequest.sendGetRequest(path, params, "UTF-8")) {
			Log.i(TAG, "success");
		} else {
			Log.i(TAG, "failure");
		}
	}
}

3:测试结果:

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

4:VideoManageAction类的内容改为

package com.capinfotech.android;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import com.opensymphony.xwork2.ActionSupport;

public class VideoManageAction extends ActionSupport implements ServletRequestAware, ServletResponseAware {

	private HttpServletRequest request;
	private HttpServletResponse response;
	
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}
	
	public void save() {
		String method = this.request.getMethod();  //获得requst的方法
		String  title = null;
		Integer timelength = null;
		try {
		if("GET".equals(method)) {
				byte[] titleByte = request.getParameter("title").getBytes("iso-8859-1");  //获得title参数对应的二进制数据
		        title = new String(titleByte, "UTF-8");
		        timelength = new Integer(request.getParameter("timelength"));  //获得参数timelength的值
				System.out.println("title: " + title);     //输出title的值
				System.out.println("timelength: " + timelength.intValue());    //输出timelength的值
			} else {
				title = request.getParameter("title");
				timelength = new Integer(request.getParameter("timelength"));
				System.out.println("title: " + title);
				System.out.println("timelength: " + timelength.intValue());
		    } 
		} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}  
	}
	
}

5:测试结果

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

android端的程序

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

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, MainActivity!</string>
    <string name="app_name">上传数据到服务器</string>
    <string name="title">视频名称</string>
    <string name="timelength">时长</string>
    <string name="button">保存</string>
    <string name="success">保存成功</string>
    <string name="error">保存失败</string>
</resources>

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

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/title"
    />
<EditText
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:id="@+id/title"
    />

<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/timelength"
    />
<EditText
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:id="@+id/timelength"
    />
<Button
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/button"
    android:text="@string/button"
/>
</LinearLayout>

3:MainActivity的内容

package com.capinfotech.upload;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.capinfotech.net.HttpRequest;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
	private static final String TAG = "MainActivity";
	
	private EditText titleEditText = null;
	private EditText timeEditText = null;
	private Button button = null;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        titleEditText = (EditText)findViewById(R.id.title);
        timeEditText = (EditText)findViewById(R.id.timelength);
        button = (Button)findViewById(R.id.button);
        
        button.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Map<String, String> params = new HashMap<String, String>();
				params.put("title", titleEditText.getText().toString());   //获取输入的视频的名字
				params.put("timelength", timeEditText.getText().toString());   //获取输入的视频的时长
				
				String path = "http://192.168.1.105/AndroidService/android/upload";  //路径
				try {
					if(HttpRequest.sendGetRequest(path, params, "UTF-8")) {
						Log.i(TAG, "success");
						Toast.makeText(MainActivity.this, R.string.success, Toast.LENGTH_LONG).show(); //提示保存成功
					} else {
						Log.i(TAG, "failure");
						Toast.makeText(MainActivity.this, R.string.error, Toast.LENGTH_LONG).show(); //提示保存失败
					}
				} catch (IOException e) {
					Log.i(TAG, "failure");
					Toast.makeText(MainActivity.this, R.string.error, Toast.LENGTH_LONG).show();
				}
			}
		});
    }
}

4:程序界面与运行效果

发表评论