get方式和post方式的區別:
1.請求的URL地址不同:
post:"http://xx:8081//servlet/LoginServlet"
get:http://xxx:8081//servlet/LoginServlet?username=root&pwd=123
2.請求頭不同:
****post方式多了幾個請求頭:Content-Length , Cache-Control , Origin
openConnection.setRequestProperty("Content-Length", body.length()+"");
openConnection.setRequestProperty("Cache-Control", "max-age=0");
openConnection.setRequestProperty("Origin", "http://xx:8081");
****post方式還多了請求的內容:username=root&pwd=123
//設置UrlConnection可以寫請求的內容
openConnection.setDoOutput(true);
//獲取一個outputstream,並將內容寫入該流
openConnection.getOutputStream().write(body.getBytes());
3.請求時攜帶的內容大小不同
get:1k
post:理論無限制
登錄的布局文件
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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" android:orientation="vertical" tools:context="com.example.yb.myapplication.MainActivity"> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/input_username" android:hint="@string/input_username"/> <EditText android:layout_marginTop="10dp" android:layout_marginBottom="10dp" android:inputType="textPassword" android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/input_password" android:hint="@string/input_password"/> <RelativeLayout android:layout_width="fill_parent" android:layout_height="wrap_content"> <CheckBox android:layout_marginLeft="30dp" android:layout_centerVertical="true" android:layout_alignParentLeft="true" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/cb_rem" android:text="@string/reme_password"/> <Button android:layout_marginRight="30dp" android:paddingLeft="10dp" android:paddingRight="10dp" android:layout_alignParentRight="true" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/bt_login" android:text="@string/bt_login"/> </RelativeLayout> </LinearLayout>
登錄的Activity代碼
public class GetPostActivity extends AppCompatActivity { private EditText et_username; private EditText et_password; private CheckBox cb_rem; private Button bt_login; private Context mcontext; private String username; private String password; private boolean isRem; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_get_post); et_username = (EditText) findViewById(R.id.input_username); et_password = (EditText) findViewById(R.id.input_password); cb_rem = (CheckBox) findViewById(R.id.cb_rem); bt_login = (Button) findViewById(R.id.bt_login); bt_login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { login(); } }); } //創建一個handler Handler handler = new Handler() { @Override public void handleMessage(Message msg) { boolean isloginsuccess = (boolean) msg.obj; if (isloginsuccess) { //判斷是否記住密碼,要保存到本地,封裝成方法 if (isRem) { //保存用戶名和密碼 boolean result = UserInfoUtil.saveUserInfo(mcontext, username, password); if (result) { Toast.makeText(getApplicationContext(), "用戶名和密碼保存成功", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(), "用戶名和密碼保存失敗", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(getApplicationContext(), "登錄成功", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(getApplicationContext(), "登錄失敗", Toast.LENGTH_SHORT).show(); } } }; public void login() { username = et_username.getText().toString().trim(); password = et_password.getText().toString().trim(); isRem = cb_rem.isChecked(); //判斷是否密碼或者用戶名為空 if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) { Toast.makeText(this, "用戶名和密碼不能為空", Toast.LENGTH_SHORT).show(); return; } //post方法登錄是否成功 LoginHttpUtil.requestNetForGetLogin(handler, username, password); } }
新建一個Net包,處理網絡請求的操作,新建一個loginhttputil.java
public class LoginHttpUtil {
//get方式登錄
public static void requestNetForGetLogin(final Handler handler,final String username,final String password) {
//在子線程中操作網絡請求
new Thread(new Runnable() {
@Override
public void run() {
//urlConnection請求服務器,驗證
try {
//1:url對象
URL url = new URL("http://192.168.1.100:8081//servlet/LoginServlet?username=" + URLEncoder.encode(username)+ "&pwd=" + URLEncoder.encode(password) + "");
//2;url.openconnection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//3
conn.setRequestMethod("GET");
conn.setConnectTimeout(10 * 1000);
//4
int code = conn.getResponseCode();
if (code == 200) {
InputStream inputStream = conn.getInputStream();
String result = StreamUtil.stremToString(inputStream);
System.out.println("=====================服務器返回的信息::" + result);
boolean isLoginsuccess=false;
if (result.contains("success")) {
isLoginsuccess=true;
}
Message msg = Message.obtain();
msg.obj=isLoginsuccess;
handler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
//post方式登錄
public static void requestNetForPOSTLogin(final Handler handler,final String username,final String password) {
new Thread(new Runnable() {
@Override
public void run() {
//urlConnection請求服務器,驗證
try {
//1:url對象
URL url = new URL("http://192.168.1.100:8081//servlet/LoginServlet");
//2;url.openconnection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//3設置請求參數
conn.setRequestMethod("POST");
conn.setConnectTimeout(10 * 1000);
//請求頭的信息
String body = "username=" + URLEncoder.encode(username) + "&pwd=" + URLEncoder.encode(password);
conn.setRequestProperty("Content-Length", String.valueOf(body.length()));
conn.setRequestProperty("Cache-Control", "max-age=0");
conn.setRequestProperty("Origin", "http://192.168.1.100:8081");
//設置conn可以寫請求的內容
conn.setDoOutput(true);
conn.getOutputStream().write(body.getBytes());
//4響應碼
int code = conn.getResponseCode();
if (code == 200) {
InputStream inputStream = conn.getInputStream();
String result = StreamUtil.stremToString(inputStream);
System.out.println("=====================服務器返回的信息::" + result);
boolean isLoginsuccess=false;
if (result.contains("success")) {
isLoginsuccess=true;
}
Message msg = Message.obtain();
msg.obj=isLoginsuccess;
handler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
二:get方式提交數據時候出現亂碼的情況l;解決辦法如下:
一般在開發客戶端和服務端的編碼要保持一致。
android端的默認編碼是utf-8;
做url請求時需要對參數進行URLEncode編碼.
URL url = new URL("http://xx:8081/servlet/LoginServlet?username="+URLEncoder.encode(username)+"&pwd="+URLEncoder.encode(password))
# 2. post方式提交數據亂碼解決
String body = "username=" + URLEncoder.encode(username) + "&pwd=" + URLEncoder.encode(password);