Android通過Get,Post,HttpClient方式提交參數給服務器

jopen 11年前發布 | 52K 次閱讀 Android Android開發 移動開發

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;
}

}</pre>

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);
}

}</pre>

服務器端代碼:

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");
}

}</pre>



 

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!