您当前的位置: 首页 > 学无止境 > 心得笔记 网站首页心得笔记
40_通过get方式提交数据到服务器
发布时间:2021-02-24 14:12:00编辑:雪饮阅读()
建立一个get接口
![servlet.png](/d/file/xuewuzhijing/xindebiji/73603143fdd39d354692a2ee8a083d0e.png)
![get.png](/d/file/xuewuzhijing/xindebiji/2be093cdae19523b4ae522e04f229fe7.png)
![servlet.png](/d/file/xuewuzhijing/xindebiji/de3c4b168f8bdf9d81b256ecc443e2d0.png)
![get.png](/d/file/xuewuzhijing/xindebiji/2b839ac4e2ea249295f3a5627d0d5dd8.png)
![get.png](/d/file/xuewuzhijing/xindebiji/a173eefb557d6d242160e86db16d2933.png)
![get.png](/d/file/xuewuzhijing/xindebiji/8496846e00e9152a60268a5fd4ea7ccc.png)
![get.png](/d/file/xuewuzhijing/xindebiji/76c317d6d7faf65da80b3e98718629fc.png)
![get.png](/d/file/xuewuzhijing/xindebiji/308f5720b1c10f041f09e29fa1c97321.png)
![get.png](/d/file/xuewuzhijing/xindebiji/7a166f6376449fbfb8da29aa76efadc0.png)
转码结果拿过来替换原来的中文参数,看看效果就没有问题了,果然是eclipse内置这个浏览器的一个url编码bug
<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>
</LinearLayout>
<string name="app_name">Login</string>
<string name="input_name">请输入用户名</string>
<string name="input_password">请输入密码</string>
<string name="get_login">采用get方式登陆</string>
</resources>
主程序MainActivity.java:
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;
@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);
}
@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);
switch (v.getId()) {
case R.id.bt_login:
// 通过get请求 发送数据到服务器
try {
StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String result = DataService.sendDataByGet(path, name, password);
Toast.makeText(this, result, 0).show();
} catch (Exception e) {
Toast.makeText(this, "访问网路异常", 0).show();
e.printStackTrace();
}
break;
}
}
}网络请求对清单文件的依赖,AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.login">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Login"
android:usesCleartextTraffic="true"
>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>建立接口地址配置文件values/config.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="servleturl">http://192.168.5.30:8080/javaweb/LoginServlet</string>
</resources>get请求的具体实现类DataService.java:
package com.example.login;
import java.io.InputStream;
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);
}
}以及依赖StreamTool.java:
package com.example.login;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
public class StreamTool {
public static byte[] getBytes(InputStream is) throws Exception{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while((len = is.read(buffer))!=-1){
bos.write(buffer, 0, len);
}
is.close();
bos.flush();
byte[] result = bos.toByteArray();
System.out.println(new String(result));
return result;
}
}
最后部署并运行,分别测试错误的登录账号与正确的登录账号,可见成功按照程序的编写逻辑运行了。
关键字词:android,servlet,get