Android发post请求, 服务器端如何获取参数

1. 如果请求中只携带参数:

public String httpPost(String urlStr, String params) {
		byte[] data = null;
		try {
			data = params.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e1) {
			return null;
		}
		URL url = null;
		HttpURLConnection connection = null;
		InputStream inputStream = null;
		String response = null;
		try {
			url = new URL(urlStr);
			connection = (HttpURLConnection)url.openConnection();
			connection.setConnectTimeout(TIME_OUT);
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setUseCaches(false);
			connection.setRequestMethod(METHOD_POST);
			connection.setRequestProperty("Connection", "Keep-Alive");
			connection.setRequestProperty("Charset", "UTF-8");
			connection.setRequestProperty("Content-Length", String.valueOf(data.length));
			connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
			connection.connect();
			DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
			outputStream.write(data);
			outputStream.flush();
			outputStream.close();
			int responseCode = connection.getResponseCode();
			if (responseCode == HTTP_OK) {
				inputStream = connection.getInputStream();
				response = getResponse(inputStream);
			} else {
				response = "返回码:" + responseCode;
			}
            Log.e(Constant.ErrorTag.register.toString(),"服务器返回字符串  "+response);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			connection.disconnect();
		}
		return response;
	}

2. 参数中携带参数及文件:

		String CRLF = "\r\n";
		String twoHyphens = "--";
		String boundary = "*****";
		HttpURLConnection con = null;
		InputStream is = null;
		DataOutputStream ds = null;
		FileInputStream videoFis = null;
        FileInputStream imageFis = null;
		
		try {

            String urlStr = Constant.baseURL;

            urlStr += Constant.UPLOAD_ACTION_PATH;

			URL url = new URL(urlStr);
			con = (HttpURLConnection) url.openConnection();

			/* 允许Input、Output,不使用Cache */
			con.setDoInput(true);
			con.setDoOutput(true);
			con.setUseCaches(false);
			/* 设置传送的method=POST */
			con.setRequestMethod("POST");
			/* setRequestProperty */
			con.setRequestProperty("Connection", "Keep-Alive");
			con.setRequestProperty("Charset", "UTF-8");
			con.setRequestProperty("Content-Type",
					"multipart/form-data;boundary=" + boundary);
            con.setChunkedStreamingMode(0);

	    /* 设置DataOutputStream */
            ds = new DataOutputStream(con.getOutputStream());
           <strong> // Send normal param.</strong>
            ds.writeBytes(twoHyphens + boundary + CRLF);
            ds.writeBytes("Content-Disposition: form-data; name=\"param\""+CRLF);
            ds.writeBytes("Content-Type: text/plain; charset=" + "UTF-8"+CRLF);
            <pre name="code" class="java">        ds.flush(); 
	ds.writeBytes(twoHyphens + boundary + CRLF); 
	int index = uploadFile.lastIndexOf("."); 
	String newName = ""; 
	String thumbnailName = ""; 
	int bufferSize = 4096; 
	byte[] buffer = new byte[bufferSize]; 
	if (Constant.VIDEO.equals(type)) {
		newName = userId + "-video." + uploadFile.substring(index+1,uploadFile.length()); 
		thumbnailName = userId + "-thumbnail.jpg";//send video file 
		ds.writeBytes("Content-Disposition: form-data; " + "name=\""+Constant.FILE_KEY_VIDEO_FROM_CLIENT+"\";filename=\"" + newName + "\"" + CRLF); 
		ds.writeBytes(CRLF); 
		videoFis = new FileInputStream(uploadFile); 
		int length = -1; 
		while ((length = videoFis.read(buffer)) != -1) {
			ds.write(buffer, 0, length); 
		}
		ds.writeBytes(CRLF); 
		ds.writeBytes(twoHyphens + boundary + CRLF); //send thumbnail 
		ds.writeBytes("Content-Disposition: form-data; " + "name=\""+Constant.FILE_KEY_IMAGE_FROM_CLIENT+"\";filename=\"" + thumbnailName + "\"" + CRLF); ds.writeBytes(CRLF); //create thumbnail at new post activity result 
		String thumbnailFile = uploadFile.replace(".mp4","-thumbnail.jpg"); 
		imageFis = new FileInputStream(thumbnailFile); 
		while ((length = imageFis.read(buffer)) != -1) { 
			ds.write(buffer, 0, length); 
		}
		ds.writeBytes(CRLF); 
		ds.writeBytes(twoHyphens + boundary + twoHyphens + CRLF); ds.flush();
		} else if(Constant.IMAGE.equals(type)) {
			newName = userId + "-image.jpg";//send image file 
			ds.writeBytes("Content-Disposition: form-data; " + "name=\""+Constant.FILE_KEY_IMAGE_FROM_CLIENT+"\";filename=\"" + newName + "\"" + CRLF); 
			ds.writeBytes(CRLF); 
			imageFis = new FileInputStream(uploadFile); 
			int length = -1; 
			while ((length = imageFis.read(buffer)) != -1) { 
				ds.write(buffer, 0, length); 
			} 
			ds.writeBytes(CRLF); 
			ds.writeBytes(twoHyphens + boundary + twoHyphens + CRLF); 
			ds.flush(); 
		}
	}

<pre name="code" class="java">

 

</pre>

            

 3. 如果在上传文件的同时还要上传多个参数: 

可以在2中send normal param时的paramValue中写多个参数拼接的字符串, 在服务器端action中用如下代码获取该字符串, 再解析成多个参数及值.

		MultiPartRequestWrapper request = (MultiPartRequestWrapper)ServletActionContext.getRequest();
		
		String param = request.getParameter("param");   //data.type=image&post.description=I'm default description
但是使用这种方法就则没有使用到struts2的参数自动注入, 所以客户端要修改为如下, 封装addParam方法, 每个param都独立使用一次
Content-Disposition: form-data; name=specificKey ....
进行注入, 不要忘记打印边界值.

封装的addParam方法如下:

    public static DataOutputStream addNormalParam(DataOutputStream ds, String paramKey, String paramValue){

        try {
            // Send normal param.
            ds.writeBytes(twoHyphens + boundary + CRLF);
            ds.writeBytes("Content-Disposition: form-data; name=\""+paramKey+"\""+CRLF);
            ds.writeBytes("Content-Type: text/plain; charset=" + "UTF-8"+CRLF);
            ds.writeBytes(CRLF+paramValue+CRLF);
            ds.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return ds;
    }

在client拼装请求时这样调用:

      ....  con.setChunkedStreamingMode(0);

			/* 设置DataOutputStream */
            ds = new DataOutputStream(con.getOutputStream());
            // Send normal param.

            HttpTool.addNormalParam(ds,"data.type",type);
            ds.writeBytes(twoHyphens + boundary + CRLF);

            HttpTool.addNormalParam(ds,"post.description",description);
			ds.writeBytes(twoHyphens + boundary + CRLF);                               
       ....

则在服务端action的data及post成员会被自动注入值.




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值