您当前的位置: 首页 > 学无止境 > 心得笔记 网站首页心得笔记
41_采用post方式提交数据到服务器
发布时间:2021-02-24 15:57:36编辑:雪饮阅读()
实现post接口
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/et_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/input_name" />
<EditText
android:id="@+id/et_password"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/input_password" />
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/get_login"
android:id="@+id/bt_login"
android:layout_alignParentRight="true"
/>
</RelativeLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/post_login"
android:id="@+id/bt_login_post"
android:layout_alignParentRight="true"
/>
</RelativeLayout>
</LinearLayout>
package com.example.login;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private EditText mEtName;
private EditText mEtPassword;
private Button mBtLogin;
private Button mBtLoginPost;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEtName = this.findViewById(R.id.et_name);
mEtPassword = this.findViewById(R.id.et_password);
mBtLogin = this.findViewById(R.id.bt_login);
mBtLogin.setOnClickListener(this);
mBtLoginPost = this.findViewById(R.id.bt_login_post);
mBtLoginPost.setOnClickListener(this);
}
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@SuppressLint("NewApi")
@Override
public void onClick(View v) {
String name = mEtName.getText().toString().trim();
String password = mEtPassword.getText().toString().trim();
if("".equals(name)||"".equals(password)){
Toast.makeText(this, "用户名或密码不能为空", 0).show();
return;
}
String path = getResources().getString(R.string.servleturl);
StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
switch (v.getId()) {
case R.id.bt_login:
// 通过get请求 发送数据到服务器
try {
String result = DataService.sendDataByGet(path, name, password);
Toast.makeText(this, result, 0).show();
} catch (Exception e) {
Toast.makeText(this, "访问网路异常", 0).show();
e.printStackTrace();
}
break;
case R.id.bt_login_post:
try {
String result = DataService.sendDataByPost(path, name, password);
Toast.makeText(this, result, 0).show();
} catch (Exception e) {
Toast.makeText(this, "访问网路异常", 0).show();
e.printStackTrace();
}
break;
}
}
}DataService.java中增加post请求的具体实现:
package com.example.login;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class DataService {
/**
* ͨ通过get请求提交数据到服务器
*
* @param path
* 服务器servlet地址
* @param name
* 用户名
* @param password
* 密码
* @return 服务器返回回来的string数据
*/
public static String sendDataByGet(String path, String name, String password)
throws Exception {
String param1 = URLEncoder.encode(name);
String param2 = URLEncoder.encode(password);
URL url = new URL(path + "?name=" + param1 + "&password=" + param2);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(5000);
// 数据并没有发送给服务器
// 获取服务器返回的流信息
InputStream is = conn.getInputStream();
byte[] result = StreamTool.getBytes(is);
return new String(result);
}
// get 一次提交的数据数据量比较小 4K 内部其实通过组拼url的方式
// post 可以提交比较大的数据 form表单的形式 流的方式写到服务器
/**
* 采用post的方式 提交数据到服务器
*
* @param path
* 服务器servlet的地址
* @param name
* 用户名
* @param password
* 密码
* @return 服务器返回的数据信息
* @throws Exception
*/
public static String sendDataByPost(String path, String name,
String password) throws Exception {
String param1 = URLEncoder.encode(name);
String param2 = URLEncoder.encode(password);
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
String data = "name=" + param1 + "&password=" + param2;
conn.setRequestMethod("POST");
conn.setConnectTimeout(5000);
// 设置 http协议可以向服务器写数据
conn.setDoOutput(true);
// 设置http协议的消息头
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", data.length() + "");
// 把我们准备好的data数据写给服务器
OutputStream os = conn.getOutputStream();
os.write(data.getBytes());
// httpurlconnection 底层实现 outputstream 是一个缓冲输出流
// 只要我们获取任何一个服务器返回的信息 , 数据就会被提交给服务器 , 得到服务器返回的流信息
int code = conn.getResponseCode();
if (code == 200) {
InputStream is = conn.getInputStream();
byte[] result = StreamTool.getBytes(is);
return new String(result);
} else {
throw new IllegalStateException("服务器状态异常");
}
}
} 最后就是在strings.xml中增加post按钮的元素值strings.xml:
<resources>
<string name="app_name">Login</string>
<string name="input_name">请输入用户名</string>
<string name="input_password">请输入密码</string>
<string name="get_login">采用get方式登陆</string>
<string name="post_login">采用post方式登陆</string>
</resources>然后部署到设备并分别测试错误账号及正确账号的post请求,如图,看来是没有问题的
关键字词:post,android