服务器端:
新建一个名为ManagerServlet的Servlet:
package cn.leigo.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ManagerServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String title = request.getParameter("title"); String timelength = request.getParameter("timelength"); System.out.println("标题:" + title); System.out.println("时长:" + timelength + "分钟"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
运行后控制台打印:
Android客户端:
LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@android:color/background_dark" android:orientation="vertical" tools:context=".MainActivity" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/title" android:textColor="@android:color/white" android:textSize="20sp" /> <EditText android:id="@+id/et_title" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="text" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/timelength" android:textColor="@android:color/white" android:textSize="20sp" /> <EditText android:id="@+id/et_timelength" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="number" /> <Button android:id="@+id/btn_save" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/save" /> </LinearLayout>
strings.xml:
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">资讯管理</string> <string name="action_settings">Settings</string> <string name="hello_world">Hello world!</string> <string name="title">资讯标题</string> <string name="timelength">资讯时长</string> <string name="save">保存</string> <string name="success">保存成功!</string> <string name="fail">保存失败!</string> <string name="error">资讯标题和资讯时长不能为空!</string> </resources>
MainActivity.java:
package cn.leigo.newsmanager; import cn.leigo.service.NewsService; import android.app.Activity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends Activity implements OnClickListener { private EditText mTitleEditText; private EditText mTimelengthEditText; private Button mSaveButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTitleEditText = (EditText) findViewById(R.id.et_title); mTimelengthEditText = (EditText) findViewById(R.id.et_timelength); mSaveButton = (Button) findViewById(R.id.btn_save); mSaveButton.setOnClickListener(this); } @Override public void onClick(View v) { String title = mTitleEditText.getText().toString(); String timelength = mTimelengthEditText.getText().toString(); if (!TextUtils.isEmpty(title) && !TextUtils.isEmpty(timelength)) { boolean isSuccess = NewsService.save(title, timelength); if (!isSuccess) { Toast.makeText(this, R.string.fail, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, R.string.success, Toast.LENGTH_SHORT) .show(); } } else { Toast.makeText(this, R.string.error, Toast.LENGTH_SHORT).show(); } } }
NewsService.java:
package cn.leigo.service; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import java.util.Map; public class NewsService { /** * 保存数据 * * @param title * 标题 * @param timelength * 时长 * @return 请求是否成功 */ public static boolean save(String title, String timelength) { String path = "http://192.168.1.100:8080/videonews/ManagerServlet"; Map<String, String> params = new HashMap<String, String>(); params.put("title", title); params.put("timelength", timelength); try { return sendGETRequest(path, params); } catch (IOException e) { e.printStackTrace(); } return false; } /** * 发送GET请求 * * @param path * 请求路径 * @param params * 请求参数 * @return * @throws IOException */ private static boolean sendGETRequest(String path, Map<String, String> params) throws IOException { // http://192.168.1.100:8080/videonews/ManagerServlet?title=abc&timelength=30 StringBuilder url = new StringBuilder(path); url.append("?"); for (Map.Entry<String, String> entry : params.entrySet()) { url.append(entry.getKey()); url.append("="); url.append(entry.getValue()); url.append("&"); } url.deleteCharAt(url.length() - 1); HttpURLConnection conn = (HttpURLConnection) new URL(url.toString()) .openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("GET"); if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { return true; } return false; } }
运行:
产生乱码原因:
1)在提交参数时,没有对中文参数进行URL编码
url.append(URLEncoder.encode(entry.getValue(), encoding));
修改后继续测试,运行
2)Tomcat服务器默认采用的是ISO8859-1编码得到参数值
String title = request.getParameter("title"); title = new String(title.getBytes("ISO8859-1"), "UTF-8");
经过这两步处理后,中文乱码问题得到了解决,但是出现一个问题,在第二步中,如果字符串有很多,每次都用
new String(title.getBytes("ISO8859-1"), "UTF-8");
这中方式解决很麻烦,咱们可以定义一个过滤器对每次穿过来的参数进行编码
EncodingFilter.java:
package cn.leigo.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; import cn.leigo.servlet.EncodingHttpServletRequest; public class EncodingFilter implements Filter { public void destroy() { } 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 { chain.doFilter(request, response); } } public void init(FilterConfig filterConfig) throws ServletException { } }
EncodingHttpServletRequest.java:
package cn.leigo.servlet; 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; } @Override public 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) { } } return value; } }
下面我们来看看使用POST方式提交数据
在WEB-INF下修改index.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form action="/web/ManageServlet" method="post"> 视频标题:<input name="title" type="text"><br/> 视频时长:<input name="timelength" type="text"><br/> <input type="submit" value=" 提 交 "/> </form> </body> </html>
修改ManagerSevlet.java:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }
点击提交
在firebug中查看信息
/** * 发送POST请求 * * @param path * 请求路径 * @param params * 请求参数 * @param encoding * 编码 * @return 请求是否成功 * @throws IOException */ private static boolean sendPOSTRequest(String path, Map<String, String> params, String encoding) throws IOException { // title=leigo&timelength=45 Content-Length 25 Content-Type // application/x-www-form-urlencoded StringBuilder data = new StringBuilder(); if (params != null && !params.isEmpty()) { for (Map.Entry<String, String> entry : params.entrySet()) { data.append(entry.getKey()); data.append("="); data.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 outputStream = conn.getOutputStream(); outputStream.write(entity); if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { return true; } return false; }
防乱码:
if ("GET".equals(req.getMethod())) { EncodingHttpServletRequest wrapper = new EncodingHttpServletRequest( req); chain.doFilter(wrapper, response); } else { req.setCharacterEncoding("UTF-8"); chain.doFilter(request, response); }
/** * 通过HttpClient发送请求 * * @param path * 请求路径 * @param params * 请求参数 * @param encoding * 编码 * @return 请求是否成功 * @throws IOException */ private static boolean sendHttpClientPOSTRequest(String path, Map<String, String> params, String encoding) throws IOException { List<NameValuePair> pairs = new ArrayList<NameValuePair>(); // 存放请求参数 for (Map.Entry<String, String> entry : params.entrySet()) { BasicNameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue()); pairs.add(pair); } UrlEncodedFormEntity 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; }
煮酒声明: 文章转自:http://blog.csdn.net/le_go/article/details/9295327