1.本篇主要实现用Get和Post提交完成登录案例。2.使用Post提交JSON数据。
代码
使用Get和Post分别实现登录案例
移动端
- NetUtil
public class NetUtil {
/**
* 使用GET访问网络
*
* @param username
* @param password
* @return 服务器返回的结果
*/
public static String loginOfGet(String username, String password) {
HttpURLConnection sConnection = null;
String data = "username=" + username + "&password=" + password;
try {
URL url = new URL("http://XXX:8080/Login?" + data);
sConnection = (HttpURLConnection) url.openConnection();
sConnection.setRequestMethod("GET");
sConnection.setConnectTimeout(10000);
sConnection.setReadTimeout(10000);
sConnection.connect();
int code = sConnection.getResponseCode();
if (code == 200) {
InputStream is = sConnection.getInputStream();
String state = getStringFromInputStream(is);
return state;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (sConnection != null) {
sConnection.disconnect();
}
}
return null;
}
/**
* 使用POST访问网络
*
* @param username
* @param password
* @return 服务器返回的结果
*/
public static String LoginOfPost(String username, String password) {
HttpURLConnection connection = null;
try {
URL url = new URL("http://XXX:8080/Login");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setConnectTimeout(10000);
connection.setReadTimeout(10000);
/**
*
* public void setDoOutput(boolean dooutput)
* 将此 URLConnection 的 doOutput 字段的值设置为指定的值.
* URL 连接可用于输入和/或输出。如果打算使用 URL 连接进行输出,
* 则将 DoOutput 标志设置为 true;如果不打算使用,则设置为 false。默认值为 false。
* 简单一句话:get请求的话默认就行了,post请求需要setDoOutput(true),这个默认是false的。
*/
connection.setDoOutput(true);
String data = "username=" + username + "&password=" + password;
OutputStream outputStream = connection.getOutputStream();
outputStream.write(data.getBytes());
outputStream.flush();
outputStream.close();
connection.connect();
if (200 == connection.getResponseCode()) {
InputStream is = connection.getInputStream();
String state = getStringFromInputStream(is);
return state;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static String getStringFromInputStream(InputStream is) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
int len = -1;
while ((len = is.read(buff)) != -1) {
baos.write(buff, 0, len);
}
is.close();
String html = baos.toString();
baos.close();
return html;
}
}
- LoginActivity
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
private String mUsername;
private String mPassword;
private static final String TAG = "LoginActivity";
private EditText mEt_usrename;
private EditText mEt_password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Button getBtn = findViewById(R.id.get_btn);
getBtn.setOnClickListener(this);
Button postBtn = findViewById(R.id.post_btn);
postBtn.setOnClickListener(this);
mEt_usrename = findViewById(R.id.et_username);
mEt_password = findViewById(R.id.et_password);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.get_btn:
mUsername = mEt_usrename.getText().toString().trim();
mPassword = mEt_password.getText().toString().trim();
Log.d(TAG, "username = "+mUsername + "password = "+mPassword);
new Thread(new Runnable() {
@Override
public void run() {
final String state = NetUtil.loginOfGet(mUsername, mPassword);
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(LoginActivity.this, "state="+state, Toast.LENGTH_SHORT).show();
}
});
}
}).start();
break;
case R.id.post_btn:
mUsername = mEt_usrename.getText().toString().trim();
mPassword = mEt_password.getText().toString().trim();
Log.d(TAG, "username = "+mUsername + "password = "+mPassword);
new Thread(new Runnable() {
@Override
public void run() {
final String state = NetUtil.LoginOfPost(mUsername, mPassword);
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(LoginActivity.this, "state="+state, Toast.LENGTH_SHORT).show();
}
});
}
}).start();
break;
}
}
- activity_login.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.wzg.jsondemo.view.LoginActivity">
<EditText
android:gravity="center"
android:id="@+id/et_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入姓名"/>
<EditText
android:gravity="center"
android:id="@+id/et_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入密码"
android:inputType="textPassword"/>
<Button
android:id="@+id/get_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Get方式提交"/>
<Button
android:text="Post方式提交"
android:id="@+id/post_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
服务端
@WebServlet(name = "LoginServlet")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println("username = "+username + "password = "+password);
if(username.equals("admin") && password.equals("123456")){
response.getWriter().println("success");
}else{
response.getWriter().println("failed");
}
}
}
向后台发送简单的Json数据
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private TextView mJsonTxt;
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
private void initViews() {
Button sendJson = findViewById(R.id.send_json);
sendJson.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.send_json:
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
// 封装CollegeStudent
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("num", 1);
jsonObject.put("name", "WangXiaoNao");
jsonObject.put("age", 20);
String s = String.valueOf(jsonObject);
Log.d(TAG, "run: ------>" + s);
URL url = new URL("http://XXX:8080/ReceiveJson");
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000);
connection.setConnectTimeout(5000);
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("User-Agent", "Fiddler");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Charset", "UTF-8");
OutputStream outputStream = connection.getOutputStream();
outputStream.write(s.getBytes());
outputStream.close();
if (200 == connection.getResponseCode()) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
String line = null;
String responseData = "";
while ((line = bufferedReader.readLine()) != null) {
responseData += line;
}
Toast.makeText(MainActivity.this, "后台返回的数据:" + responseData, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
break;
}
}
}