MyException - 我的异常网
当前位置:我的异常网» 操作系统 » Android之透过Get,Post,HttpClient方式提交参数给服

Android之透过Get,Post,HttpClient方式提交参数给服务器

www.MyException.Cn  网友分享于:2015-08-26  浏览:43次
Android之通过Get,Post,HttpClient方式提交参数给服务器

一:服务器端

0:Web.xml

  <?xml version="1.0" encoding="UTF-8" ?> 
- <web-app id="WebApp_ID" 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>videoweb</display-name> 
- <filter>
  <display-name>EncodingFilter</display-name> 
  <filter-name>EncodingFilter</filter-name> 
  <filter-class>cn.itcast.filter.EncodingFilter</filter-class> 
  </filter>
- <filter-mapping>
  <filter-name>EncodingFilter</filter-name> 
  <url-pattern>*.do</url-pattern>//在这里会过滤掉所有的.do文件,系统自动进行的,不用刻意在代码里面调用 
  </filter-mapping>                        //EncodingFilter的java类
- <servlet>
  <servlet-name>struts</servlet-name> 
  <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> 
- <init-param>
  <param-name>config</param-name> 
  <param-value>/WEB-INF/struts-config.xml</param-value> 
  </init-param>
  </servlet>
- <servlet-mapping>
  <servlet-name>struts</servlet-name> 
  <url-pattern>*.do</url-pattern> 
  </servlet-mapping>
- <welcome-file-list>
  <welcome-file>index.jsp</welcome-file> 
  </welcome-file-list>
  </web-app>

 

1:struts-config.xml

  <?xml version="1.0" encoding="UTF-8" ?> 
  <!DOCTYPE struts-config (View Source for full doctype...)> 
- <struts-config>
- <form-beans>
  <form-bean name="videoForm" type="cn.itcast.formbean.VideoForm" /> 
  </form-beans>
- <action-mappings>
- <action path="/video/list" name="videoForm" scope="request" type="cn.itcast.action.VideoListAction">
  <forward name="video" path="/WEB-INF/page/videos.jsp" /> 
  <forward name="jsonvideo" path="/WEB-INF/page/jsonvideos.jsp" /> 
  </action>
- <action path="/video/manage" name="videoForm" scope="request" type="cn.itcast.action.VideoManageAction" parameter="method">
  <forward name="result" path="/WEB-INF/page/result.jsp" /> 
  </action>
  </action-mappings>
  </struts-config>

 2:EncodingFilter

package cn.itcast.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;

public class EncodingFilter implements Filter {

	public void destroy() {
		// TODO Auto-generated method stub
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
		req.setCharacterEncoding("UTF-8");
		chain.doFilter(request, response);
	}

	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}

 

3:VideoForm

package cn.itcast.formbean;

import org.apache.struts.action.ActionForm;
import org.apache.struts.upload.FormFile;

public class VideoForm extends ActionForm {
	private String format;
	private String title;	
	private Integer timelength;
	private FormFile video;
	
	public FormFile getVideo() {
		return video;
	}

	public void setVideo(FormFile video) {
		this.video = video;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public Integer getTimelength() {
		return timelength;
	}

	public void setTimelength(Integer timelength) {
		this.timelength = timelength;
	}

	public String getFormat() {
		return format;
	}

	public void setFormat(String format) {
		this.format = format;
	}
	
}

 

4:VideoManageAction.java

package cn.itcast.action;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

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

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import cn.itcast.formbean.VideoForm;
import cn.itcast.utils.StreamTool;

public class VideoManageAction extends DispatchAction {
	
	public ActionForward save(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		VideoForm formbean = (VideoForm)form;
		if("GET".equals(request.getMethod())){
			byte[] data = request.getParameter("title").getBytes("ISO-8859-1");
			String title = new String(data, "UTF-8");
			System.out.println("title:"+ title);
			System.out.println("timelength:"+ formbean.getTimelength());
		}else{
			System.out.println("title:"+ formbean.getTitle());
			System.out.println("timelength:"+ formbean.getTimelength());
		}
		//下面完成视频文件的保存
		if(formbean.getVideo()!=null && formbean.getVideo().getFileSize()>0){
			String realpath = request.getSession().getServletContext().getRealPath("/video");
			System.out.println(realpath);
			File dir = new File(realpath);
			if(!dir.exists()) dir.mkdirs();
			File videoFile = new File(dir, formbean.getVideo().getFileName());
			FileOutputStream outStream = new FileOutputStream(videoFile);
			outStream.write(formbean.getVideo().getFileData());
			outStream.close();
		}
		return mapping.findForward("result");
	}
	
	public ActionForward getXML(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		InputStream inStream = request.getInputStream();
		byte[] data = StreamTool.readInputStream(inStream);
		String xml = new String(data, "UTF-8");
		System.out.println(xml);
		return mapping.findForward("result");
	}
}

 

5:result.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>
	保存完成
</body>
</html>

 

二:客户端

1:HttpRequest

package cn.itcast.net;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

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 org.xmlpull.v1.XmlPullParser;

import android.util.Xml;

import cn.itcast.utils.StreamTool;

public class HttpRequest {

	
	public static boolean sendXML(String path, String xml)throws Exception{
		byte[] data = xml.getBytes();
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection)url.openConnection();
		conn.setRequestMethod("POST");
		conn.setConnectTimeout(5 * 1000);
		conn.setDoOutput(true);//如果通过post提交数据,必须设置允许对外输出数据
		conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
		conn.setRequestProperty("Content-Length", String.valueOf(data.length));
		OutputStream outStream = conn.getOutputStream();
		outStream.write(data);
		outStream.flush();
		outStream.close();
		if(conn.getResponseCode()==200){
			return true;
		}
		return false;
	}

	public static boolean sendGetRequest(String path, Map<String, String> params, String enc) throws Exception{
		StringBuilder sb = new StringBuilder(path);
		sb.append('?');
		// ?method=save&title=435435435&timelength=89&
		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);
		
		URL url = new URL(sb.toString());
		HttpURLConnection conn = (HttpURLConnection)url.openConnection();
		conn.setRequestMethod("GET");
		conn.setConnectTimeout(5 * 1000);
		if(conn.getResponseCode()==200){
			return true;
		}
		return false;
	}
	
	public static boolean sendPostRequest(String path, Map<String, String> params, String enc) throws Exception{
		// title=dsfdsf&timelength=23&method=save
		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(), enc)).append('&');
			}
			sb.deleteCharAt(sb.length()-1);
		}
		byte[] entitydata = sb.toString().getBytes();//得到实体的二进制数据
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection)url.openConnection();
		conn.setRequestMethod("POST");
		conn.setConnectTimeout(5 * 1000);
		conn.setDoOutput(true);//如果通过post提交数据,必须设置允许对外输出数据
		//Content-Type: application/x-www-form-urlencoded
		//Content-Length: 38
		conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		conn.setRequestProperty("Content-Length", String.valueOf(entitydata.length));
		OutputStream outStream = conn.getOutputStream();
		outStream.write(entitydata);
		outStream.flush();
		outStream.close();
		if(conn.getResponseCode()==200){
			return true;
		}
		return false;
	}
	
	//SSL HTTPS Cookie
	public static boolean sendRequestFromHttpClient(String path, Map<String, String> params, String enc) 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, enc);//得到经过编码过后的实体数据
		HttpPost post = new HttpPost(path); //form
		post.setEntity(entitydata);
		DefaultHttpClient client = new DefaultHttpClient(); //浏览器
		HttpResponse response = client.execute(post);//执行请求
		if(response.getStatusLine().getStatusCode()==200){
			return true;
		}
		return false;
	}
}

  2:MainActivity

package cn.itcast.uploaddata;

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

import cn.itcast.net.HttpRequest;
import cn.itcast.utils.FormFile;
import cn.itcast.utils.SocketHttpRequester;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
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 timelengthText;
    private EditText titleText;
    private EditText videoText;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
       Button button = (Button) this.findViewById(R.id.button);
       timelengthText = (EditText) this.findViewById(R.id.timelength);
       videoText = (EditText) this.findViewById(R.id.video);
       titleText = (EditText) this.findViewById(R.id.title);
       button.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				String title = titleText.getText().toString();
				String timelength = timelengthText.getText().toString();
				Map<String, String> params = new HashMap<String, String>();
				params.put("method", "save");
				params.put("title", title);
				params.put("timelength", timelength);
				try {
					HttpRequest.sendGetRequest("http://192.168.1.100:8080/videoweb/video/manage.do", params, "UTF-8");
										Toast.makeText(MainActivity.this, R.string.success, 1).show();
				} catch (Exception e) {
					Toast.makeText(MainActivity.this, R.string.error, 1).show();
					Log.e(TAG, e.toString());
				}
			}
		});
        
    }
}

 3:测试类:HttpRequestTest

package cn.itcast.uploaddata;

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

import cn.itcast.net.HttpRequest;
import android.test.AndroidTestCase;
import android.util.Log;

public class HttpRequestTest extends AndroidTestCase {
	private static final String TAG = "HttpRequestTest";
	
	public void testSendXMLRequest() throws Throwable{
		String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><persons><person id=\"23\"><name>liming</name><age>30</age></person></persons>";
		HttpRequest.sendXML("http://192.168.1.100:8080/videoweb/video/manage.do?method=getXML", xml);
	}

	public void testSendGetRequest() throws Throwable{
		//?method=save&title=xxxx&timelength=90
		Map<String, String> params = new HashMap<String, String>();
		params.put("method", "save");
		params.put("title", "liming");
		params.put("timelength", "80");
		
		HttpRequest.sendGetRequest("http://192.168.1.100:8080/videoweb/video/manage.do", params, "UTF-8");
	}
	
	public void testSendPostRequest() throws Throwable{
		Map<String, String> params = new HashMap<String, String>();
		params.put("method", "save");
		params.put("title", "中国");
		params.put("timelength", "80");
		
		HttpRequest.sendPostRequest("http://192.168.1.100:8080/videoweb/video/manage.do", params, "UTF-8");
	}
	
	public void testSendRequestFromHttpClient() throws Throwable{
		Map<String, String> params = new HashMap<String, String>();
		params.put("method", "save");
		params.put("title", "传智播客");
		params.put("timelength", "80");
		
		boolean result = HttpRequest.sendRequestFromHttpClient("http://192.168.1.100:8080/videoweb/video/manage.do", params, "UTF-8");
		Log.i("HttRequestTest", ""+ result);
	}
}

 

文章评论

科技史上最臭名昭著的13大罪犯
科技史上最臭名昭著的13大罪犯
要嫁就嫁程序猿—钱多话少死的早
要嫁就嫁程序猿—钱多话少死的早
初级 vs 高级开发者 哪个性价比更高?
初级 vs 高级开发者 哪个性价比更高?
10个帮程序员减压放松的网站
10个帮程序员减压放松的网站
我的丈夫是个程序员
我的丈夫是个程序员
中美印日四国程序员比较
中美印日四国程序员比较
5款最佳正则表达式编辑调试器
5款最佳正则表达式编辑调试器
每天工作4小时的程序员
每天工作4小时的程序员
“懒”出效率是程序员的美德
“懒”出效率是程序员的美德
漫画:程序员的工作
漫画:程序员的工作
编程语言是女人
编程语言是女人
为啥Android手机总会越用越慢?
为啥Android手机总会越用越慢?
总结2014中国互联网十大段子
总结2014中国互联网十大段子
一个程序员的时间管理
一个程序员的时间管理
聊聊HTTPS和SSL/TLS协议
聊聊HTTPS和SSL/TLS协议
老美怎么看待阿里赴美上市
老美怎么看待阿里赴美上市
不懂技术不要对懂技术的人说这很容易实现
不懂技术不要对懂技术的人说这很容易实现
程序员的一天:一寸光阴一寸金
程序员的一天:一寸光阴一寸金
团队中“技术大拿”并非越多越好
团队中“技术大拿”并非越多越好
代码女神横空出世
代码女神横空出世
十大编程算法助程序员走上高手之路
十大编程算法助程序员走上高手之路
程序员最害怕的5件事 你中招了吗?
程序员最害怕的5件事 你中招了吗?
旅行,写作,编程
旅行,写作,编程
Web开发者需具备的8个好习惯
Web开发者需具备的8个好习惯
我是如何打败拖延症的
我是如何打败拖延症的
看13位CEO、创始人和高管如何提高工作效率
看13位CEO、创始人和高管如何提高工作效率
为什么程序员都是夜猫子
为什么程序员都是夜猫子
那些性感的让人尖叫的程序员
那些性感的让人尖叫的程序员
Web开发人员为什么越来越懒了?
Web开发人员为什么越来越懒了?
程序员应该关注的一些事儿
程序员应该关注的一些事儿
做程序猿的老婆应该注意的一些事情
做程序猿的老婆应该注意的一些事情
Google伦敦新总部 犹如星级庄园
Google伦敦新总部 犹如星级庄园
如何成为一名黑客
如何成为一名黑客
那些争议最大的编程观点
那些争议最大的编程观点
当下全球最炙手可热的八位少年创业者
当下全球最炙手可热的八位少年创业者
程序员都该阅读的书
程序员都该阅读的书
鲜为人知的编程真相
鲜为人知的编程真相
2013年中国软件开发者薪资调查报告
2013年中国软件开发者薪资调查报告
老程序员的下场
老程序员的下场
程序员眼里IE浏览器是什么样的
程序员眼里IE浏览器是什么样的
程序员的鄙视链
程序员的鄙视链
程序员和编码员之间的区别
程序员和编码员之间的区别
Java程序员必看电影
Java程序员必看电影
程序员必看的十大电影
程序员必看的十大电影
10个调试和排错的小建议
10个调试和排错的小建议
亲爱的项目经理,我恨你
亲爱的项目经理,我恨你
程序猿的崛起——Growth Hacker
程序猿的崛起——Growth Hacker
Java 与 .NET 的平台发展之争
Java 与 .NET 的平台发展之争
60个开发者不容错过的免费资源库
60个开发者不容错过的免费资源库
软件开发程序错误异常ExceptionCopyright © 2009-2015 MyException 版权所有