Android 使用Post方式提交数据

时间:2022-10-22 05:16:23

在Android中,提供了标准Java接口HttpURLConnection和Apache接口HttpClient,为客户端HTTP编程提供了丰富的支持。

  在HTTP通信中使用最多的就是GET和POST了,GET请求可以获取静态页面,也可以把参数放在URL字符串的后面,传递给服务器。POST与GET的不同之处在于POST的参数不是放在URL字符串里面,而是放在HTTP请求数据中。

  本文将使用标准Java接口HttpURLConnection,以一个实例演示如何使用POST方式向服务器提交数据,并将服务器的响应结果显示在Android客户端

1.Android中实现

activity_main.xml部分

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" > <TextView
android:id="@+id/lblPostResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/butPost"
android:layout_centerHorizontal="true"
android:text="提交结果" /> <Button
android:id="@+id/butPost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="25dp"
android:text="提交测试" /> </RelativeLayout>

//import部分

//import部分
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.util.Log; import java.io.InputStream;
import java.util.HashMap;
import java.util.Map; import java.util.Date;
import java.text.SimpleDateFormat;

//public class MainActivity extends Activity  部分

private Button m_butPost;
m_butPost=(Button)findViewById(R.id.butPost);
m_butPost.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
butPost_OnClick(v);
}
}); //提交测试
private void butPost_OnClick(View v){
//请求参数键-值对
String strRecSmsMsg="收短信测试";
//提交
RecSmsToPost(strRecSmsMsg);
openToast("提交测试完成");
}
//收到短信 后 提交
private void RecSmsToPost(String strRecSmsMsg){
String strNowDateTime=getNowDateTime("yyyy-MM-dd|HH:mm:ss");//当前时间
//参数
Map<String,String> params = new HashMap<String,String>();
params.put("RECSMSMSG", strRecSmsMsg);
//params.put("name", "李四"); //服务器请求路径
String strUrlPath = "http://192.168.1.9:80/JJKSms/RecSms.php" +"?DateTime=" + strNowDateTime;
String strResult=HttpUtils.submitPostData(strUrlPath,params, "utf-8");
m_lblPostResult.setText(strResult); //openToast("提交完成");
} //获取当前时间
private String getNowDateTime(String strFormat){
if(strFormat==""){
strFormat="yyyy-MM-dd HH:mm:ss";
}
Date now = new Date();
SimpleDateFormat df = new SimpleDateFormat(strFormat);//设置日期格式
return df.format(now); // new Date()为获取当前系统时间
} //弹出消息
private void openToast(String strMsg){
Toast.makeText(this, strMsg, Toast.LENGTH_LONG).show();
}

HttpUtils 类部分

新建 类文件 HttpUtils 其中代码如下:

import java.net.HttpURLConnection;
import java.net.URL;
import java.io.OutputStream;
import java.io.InputStream;
import java.util.Map;
import java.io.IOException;
import java.net.URLEncoder;
import java.io.ByteArrayOutputStream; public class HttpUtils {
/*
* Function : 发送Post请求到服务器
* Param : params请求体内容,encode编码格式
*/
public static String submitPostData(String strUrlPath,Map<String, String> params, String encode) { byte[] data = getRequestData(params, encode).toString().getBytes();//获得请求体
try { //String urlPath = "http://192.168.1.9:80/JJKSms/RecSms.php";
URL url = new URL(strUrlPath); HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setConnectTimeout(3000); //设置连接超时时间
httpURLConnection.setDoInput(true); //打开输入流,以便从服务器获取数据
httpURLConnection.setDoOutput(true); //打开输出流,以便向服务器提交数据
httpURLConnection.setRequestMethod("POST"); //设置以Post方式提交数据
httpURLConnection.setUseCaches(false); //使用Post方式不能使用缓存
//设置请求体的类型是文本类型
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//设置请求体的长度
httpURLConnection.setRequestProperty("Content-Length", String.valueOf(data.length));
//获得输出流,向服务器写入数据
OutputStream outputStream = httpURLConnection.getOutputStream();
outputStream.write(data); int response = httpURLConnection.getResponseCode(); //获得服务器的响应码
if(response == HttpURLConnection.HTTP_OK) {
InputStream inptStream = httpURLConnection.getInputStream();
return dealResponseResult(inptStream); //处理服务器的响应结果
}
} catch (IOException e) {
//e.printStackTrace();
return "err: " + e.getMessage().toString();
}
return "-1";
} /*
* Function : 封装请求体信息
* Param : params请求体内容,encode编码格式
*/
public static StringBuffer getRequestData(Map<String, String> params, String encode) {
StringBuffer stringBuffer = new StringBuffer(); //存储封装好的请求体信息
try {
for(Map.Entry<String, String> entry : params.entrySet()) {
stringBuffer.append(entry.getKey())
.append("=")
.append(URLEncoder.encode(entry.getValue(), encode))
.append("&");
}
stringBuffer.deleteCharAt(stringBuffer.length() - 1); //删除最后的一个"&"
} catch (Exception e) {
e.printStackTrace();
}
return stringBuffer;
} /*
* Function : 处理服务器的响应结果(将输入流转化成字符串)
* Param : inputStream服务器的响应输入流
*/
public static String dealResponseResult(InputStream inputStream) {
String resultData = null; //存储处理结果
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int len = 0;
try {
while((len = inputStream.read(data)) != -1) {
byteArrayOutputStream.write(data, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}
resultData = new String(byteArrayOutputStream.toByteArray());
return resultData;
} }

2.服务器端的准备

  在服务器端我采用wamp方式,当然其它方式也可以。 创建RecSms.php 文件 内容如下:

<?php

require_once ('Log/LogHelper.php');

echo "你好" . "post </br>";

foreach($_REQUEST as $k=>$v){
echo $k;echo "--";
echo $v;echo "</br>";
} WriteLog('你好 RecSms.php ---------'); foreach($_POST as $k=>$v){
WriteLog( $k .'--' .$v);
}
foreach($_GET as $k=>$v){
WriteLog( $k .'--' .$v);
} ?>

将提交的数据写入Log\Log.php文件中。

其中LogHelper.php 为写日志文件,代码文件如下:

<?php 

function WriteLog($msg){
$fp = fopen("Log\Log.php", "a");//文件被清空后再写入
if($fp)
{
date_default_timezone_set('asia/chongqing');
$time=date("H:i:s",strtotime("now"));
$flag=fwrite($fp, $time ." ".$msg ." \r\n");
fclose($fp);
}
}
?>

所有代码已写好。

开启 wamp ,在Android中点击 提交测试 则 在Log.php文件写入提交的数据