歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Struts2+Android 多種方式向服務器發送信息

Struts2+Android 多種方式向服務器發送信息

日期:2017/3/1 10:22:21   编辑:Linux編程

還是接上篇 Struts2+Android 實現信息,文件上傳功能

修改了一些VideoManageAction

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

這次使用TestCase 用的時候加如activity吧

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

更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11

Copyright © Linux教程網 All Rights Reserved