Struts2+Android 多种方式向服务器发送信息


还是接上篇 Struts2+Android 实现信息,文件上传功能

修改了一些VideoManageAction

  1. package com.su.action;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileOutputStream;  
  6. import java.io.InputStream;  
  7. import java.io.OutputStream;  
  8. import java.text.SimpleDateFormat;  
  9. import java.util.Date;  
  10.   
  11. import javax.servlet.http.HttpServletRequest;  
  12. import javax.servlet.http.HttpServletResponse;  
  13. import org.apache.struts2.ServletActionContext;  
  14.   
  15. import com.opensymphony.xwork2.ActionSupport;  
  16. import com.su.action.util.StreamTool;  
  17.   
  18.   
  19.   
  20. public class VideoManageAction extends ActionSupport {  
  21.     private String title;  
  22.     private String timelength;  
  23.     private File myFile;  
  24.     private String myFileFileName;  
  25.     public String getMethod() {  
  26.         return method;  
  27.     }  
  28.   
  29.     public void setMethod(String method) {  
  30.         this.method = method;  
  31.     }  
  32.   
  33.     private String method;  
  34.     public File getMyFile() {  
  35.         return myFile;  
  36.     }  
  37.   
  38.     public void setMyFile(File myFile) {  
  39.         this.myFile = myFile;  
  40.     }  
  41.   
  42.     public String getTitle() {  
  43.         return title;  
  44.     }  
  45.   
  46.     public void setTitle(String title) {  
  47.         this.title = title;  
  48.     }  
  49.   
  50.     public String getTimelength() {  
  51.         return timelength;  
  52.     }  
  53.   
  54.     public void setTimelength(String timelength) {  
  55.         this.timelength = timelength;  
  56.     }  
  57.   
  58.     public void setMyFileFileName(String myFileFileName) {  
  59.         this.myFileFileName = myFileFileName;  
  60.     }  
  61.   
  62.       
  63.   
  64.     public String getMyFileFileName() {  
  65.         return myFileFileName;  
  66.     }  
  67.   
  68.     public String execute() throws Exception {  
  69.         if (method.equals("getXml")) {  
  70.             InputStream inStream = ServletActionContext.getRequest().getInputStream();  
  71.             byte[] data = StreamTool.readInputStream(inStream);  
  72.             String xml = new String(data, "UTF-8");  
  73.             System.out.println("11111111111111111111");  
  74.             System.out.println(xml);  
  75.         }  
  76.         if (myFile!=null) {  
  77.           
  78.         InputStream is = new FileInputStream(myFile);  
  79.         String uploadPath = ServletActionContext.getServletContext()  
  80.                 .getRealPath("/upload");  
  81.         File file = new File(uploadPath);  
  82.           
  83.         if (!file.exists()) {  
  84.             file.mkdir();  
  85.               
  86.               
  87.         }  
  88.         File toFile = new File(uploadPath, this.getMyFileFileName());  
  89.   
  90.         OutputStream os = new FileOutputStream(toFile);  
  91.   
  92.         byte[] buffer = new byte[1024];  
  93.   
  94.         int length = 0;  
  95.   
  96.         while ((length = is.read(buffer)) > 0) {  
  97.             os.write(buffer, 0, length);  
  98.         }  
  99.           
  100.         is.close();  
  101.         os.close();  
  102.         }  
  103.         System.out.println(this.getTimelength()+"\n"+this.getTitle()+"\n");  
  104.         return SUCCESS;  
  105.   
  106.     }  
  107. }  

这次使用TestCase 用的时候加如activity吧

  1. package cn.itcast.uploaddata;  
  2.   
  3. import java.io.InputStream;  
  4. import java.util.HashMap;  
  5. import java.util.Map;  
  6.   
  7. import cn.itcast.net.HttpRequest;  
  8. import android.test.AndroidTestCase;  
  9. import android.util.Log;  
  10.   
  11. public class HttpRequestTest extends AndroidTestCase {  
  12.     private static final String TAG = "HttpRequestTest";  
  13.       
  14.     public void testSendXMLRequest() throws Throwable{  
  15.         String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><persons><person id=\"23\"><name>liming</name><age>30</age></person></persons>";  
  16.         HttpRequest.sendXML("http://10.1.27.35:8080/VideoWeb2/upload.action?method=getXml", xml);  
  17.     }  
  18.   
  19.     public void testSendGetRequest() throws Throwable{  
  20.         //?method=save&title=xxxx&timelength=90   
  21.         Map<String, String> params = new HashMap<String, String>();  
  22.         //params.put("method", "save");   
  23.         params.put("title""liming");  
  24.         params.put("timelength""80");  
  25.         HttpRequest.sendGetRequest("http://10.1.27.35:8080/VideoWeb2/upload.action", params, "UTF-8");  
  26.     }  
  27.       
  28.     public void testSendPostRequest() throws Throwable{  
  29.         Map<String, String> params = new HashMap<String, String>();  
  30.         //params.put("method", "save");   
  31.         params.put("title""中国");  
  32.         params.put("timelength""80");  
  33.           
  34.         HttpRequest.sendPostRequest("http://10.1.27.35:8080/VideoWeb2/upload.action", params, "UTF-8");  
  35.     }  
  36.       
  37.     public void testSendRequestFromHttpClient() throws Throwable{  
  38.         Map<String, String> params = new HashMap<String, String>();  
  39.         //params.put("method", "save");   
  40.         params.put("title""传智播客");  
  41.         params.put("timelength""80");  
  42.           
  43.         boolean result = HttpRequest.sendRequestFromHttpClient("http://10.1.27.35:8080/VideoWeb2/upload.action", params, "UTF-8");  
  44.         Log.i("HttRequestTest"""+ result);  
  45.     }  
  46. }  
 
  1. package cn.itcast.net;  
  2.   
  3. import java.io.InputStream;  
  4. import java.io.OutputStream;  
  5. import java.net.HttpURLConnection;  
  6. import java.net.URL;  
  7. import java.net.URLEncoder;  
  8. import java.util.ArrayList;  
  9. import java.util.HashMap;  
  10. import java.util.List;  
  11. import java.util.Map;  
  12. import java.util.regex.Matcher;  
  13. import java.util.regex.Pattern;  
  14.   
  15. import org.apache.http.HttpResponse;  
  16. import org.apache.http.NameValuePair;  
  17. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  18. import org.apache.http.client.methods.HttpPost;  
  19. import org.apache.http.impl.client.DefaultHttpClient;  
  20. import org.apache.http.message.BasicNameValuePair;  
  21. import org.xmlpull.v1.XmlPullParser;  
  22.   
  23. import android.util.Xml;  
  24.   
  25. import cn.itcast.utils.StreamTool;  
  26.   
  27. public class HttpRequest {  
  28.   
  29.       
  30.     public static boolean sendXML(String path, String xml)throws Exception{  
  31.         byte[] data = xml.getBytes();  
  32.         URL url = new URL(path);  
  33.         HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
  34.         conn.setRequestMethod("POST");  
  35.         conn.setConnectTimeout(5 * 1000);  
  36.         conn.setDoOutput(true);//如果通过post提交数据,必须设置允许对外输出数据   
  37.         conn.setRequestProperty("Content-Type""text/xml; charset=UTF-8");  
  38.         conn.setRequestProperty("Content-Length", String.valueOf(data.length));  
  39.         OutputStream outStream = conn.getOutputStream();  
  40.         outStream.write(data);  
  41.         outStream.flush();  
  42.         outStream.close();  
  43.         if(conn.getResponseCode()==200){  
  44.             return true;  
  45.         }  
  46.         return false;  
  47.     }  
  48.   
  49.     public static boolean sendGetRequest(String path, Map<String, String> params, String enc) throws Exception{  
  50.         StringBuilder sb = new StringBuilder(path);  
  51.         sb.append('?');  
  52.         // ?method=save&title=435435435&timelength=89&   
  53.         for(Map.Entry<String, String> entry : params.entrySet()){  
  54.             sb.append(entry.getKey()).append('=')  
  55.                 .append(URLEncoder.encode(entry.getValue(), enc)).append('&');  
  56.         }  
  57.         sb.deleteCharAt(sb.length()-1);  
  58.           
  59.         URL url = new URL(sb.toString());  
  60.         HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
  61.         conn.setRequestMethod("GET");  
  62.         conn.setConnectTimeout(5 * 1000);  
  63.         if(conn.getResponseCode()==200){  
  64.             return true;  
  65.         }  
  66.         return false;  
  67.     }  
  68.       
  69.     public static boolean sendPostRequest(String path, Map<String, String> params, String enc) throws Exception{  
  70.         // title=dsfdsf&timelength=23&method=save   
  71.         StringBuilder sb = new StringBuilder();  
  72.         if(params!=null && !params.isEmpty()){  
  73.             for(Map.Entry<String, String> entry : params.entrySet()){  
  74.                 sb.append(entry.getKey()).append('=')  
  75.                     .append(URLEncoder.encode(entry.getValue(), enc)).append('&');  
  76.             }  
  77.             sb.deleteCharAt(sb.length()-1);  
  78.         }  
  79.         byte[] entitydata = sb.toString().getBytes();//得到实体的二进制数据   
  80.         URL url = new URL(path);  
  81.         HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
  82.         conn.setRequestMethod("POST");  
  83.         conn.setConnectTimeout(5 * 1000);  
  84.         conn.setDoOutput(true);//如果通过post提交数据,必须设置允许对外输出数据   
  85.         //Content-Type: application/x-www-form-urlencoded   
  86.         //Content-Length: 38   
  87.         conn.setRequestProperty("Content-Type""application/x-www-form-urlencoded");  
  88.         conn.setRequestProperty("Content-Length", String.valueOf(entitydata.length));  
  89.         OutputStream outStream = conn.getOutputStream();  
  90.         outStream.write(entitydata);  
  91.         outStream.flush();  
  92.         outStream.close();  
  93.         if(conn.getResponseCode()==200){  
  94.             return true;  
  95.         }  
  96.         return false;  
  97.     }  
  98.       
  99.     //SSL HTTPS Cookie   
  100.     public static boolean sendRequestFromHttpClient(String path, Map<String, String> params, String enc) throws Exception{  
  101.         List<NameValuePair> paramPairs = new ArrayList<NameValuePair>();  
  102.         if(params!=null && !params.isEmpty()){  
  103.             for(Map.Entry<String, String> entry : params.entrySet()){  
  104.                 paramPairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));  
  105.             }  
  106.         }  
  107.         UrlEncodedFormEntity entitydata = new UrlEncodedFormEntity(paramPairs, enc);//得到经过编码过后的实体数据   
  108.         HttpPost post = new HttpPost(path); //form   
  109.         post.setEntity(entitydata);  
  110.         DefaultHttpClient client = new DefaultHttpClient(); //浏览器   
  111.         HttpResponse response = client.execute(post);//执行请求   
  112.         if(response.getStatusLine().getStatusCode()==200){  
  113.             return true;  
  114.         }  
  115.         return false;  
  116.     }  
  117. }  
 

更多Android相关信息见Android 专题页面 http://www.bkjia.com/topicnews.aspx?tid=11

相关内容