作者:阿思翠 | 来源:互联网 | 2023-01-01 10:54
1.使用HttpURLConnection实现post和get请求数据:(1)NetUtils类:publicclassNetUtils{privatestaticf
1.使用HttpURLConnection实现post和get请求数据:
(1)NetUtils类:
public class NetUtils {
private static final String TAG = "NetUtils";
/**
* 使用post的方式登录
* @param userName
* @param password
* @return
*/
public static String loginOfPost(String userName, String password) {
HttpURLConnection cOnn= null;
try {
URL url = new URL("http://10.0.2.2:8080/ServerItheima/servlet/LoginServlet");
cOnn= (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(10000);
conn.setReadTimeout(5000);
conn.setDoOutput(true);
String data = "username=" + userName + "&password=" + password;
OutputStream out = conn.getOutputStream();
out.write(data.getBytes());
out.flush();
out.close();
int respOnseCode= conn.getResponseCode();
if(respOnseCode== 200) {
InputStream is = conn.getInputStream();
String state = getStringFromInputStream(is);
return state;
} else {
Log.i(TAG, "访问失败: " + responseCode);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(conn != null) {
conn.disconnect();
}
}
return null;
}
/**
* 使用get的方式登录
* @param userName
* @param password
* @return 登录的状态
*/
public static String loginOfGet(String userName, String password) {
HttpURLConnection cOnn= null;
try {
String data = "username=" + URLEncoder.encode(userName) + "&password=" + URLEncoder.encode(password);
URL url = new URL("http://10.0.2.2:8080/ServerItheima/servlet/LoginServlet?" + data);
cOnn= (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(10000);
conn.setReadTimeout(5000);
int respOnseCode= conn.getResponseCode();
if(respOnseCode== 200) {
InputStream is = conn.getInputStream();
String state = getStringFromInputStream(is);
return state;
} else {
Log.i(TAG, "访问失败: " + responseCode);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(conn != null) {
conn.disconnect();
}
}
return null;
}
/**
* 根据流返回一个字符串信息
* @param is
* @return
* @throws IOException
*/
private static String getStringFromInputStream(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
is.close();
String html = baos.toString();
baos.close();
return html;
}
业务逻辑的实现代码(自己写的);
public class MainActivity extends Activity {
private EditText etUserName;
private EditText etPassword;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etUserName = (EditText) findViewById(R.id.et_username);
etPassword = (EditText) findViewById(R.id.et_password);
}
public void doGet(View v) {
final String userName = etUserName.getText().toString();
final String password = etPassword.getText().toString();
new Thread(
new Runnable() {
@Override
public void run() {
final String state = NetUtils.loginOfGet(userName, password);
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, state, 0).show();
}
});
}
}).start();
}
public void doPost(View v) {
final String userName = etUserName.getText().toString();
final String password = etPassword.getText().toString();
new Thread(new Runnable() {
@Override
public void run() {
final String state = NetUtils.loginOfPost(userName, password);
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, state, 0).show();
}
});
}
}).start();
}
2.使用httpClinet
public class NetUtils2 {
private static final String TAG = "NetUtils";
/**
* 使用post的方式登录
* @param userName
* @param password
* @return
*/
public static String loginOfPost(String userName, String password) {
HttpClient client = null;
try {
client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://10.0.2.2:8080/ServerItheima/servlet/LoginServlet");
List parameters = new ArrayList();
parameters.add(new BasicNameValuePair("username", userName));
parameters.add(new BasicNameValuePair("password", password));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "utf-8");
post.setEntity(entity);
HttpResponse respOnse= client.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode == 200) {
InputStream is = response.getEntity().getContent();
String text = getStringFromInputStream(is);
return text;
} else {
Log.i(TAG, "请求失败: " + statusCode);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(client != null) {
client.getConnectionManager().shutdown();
}
}
return null;
}
/**
* 使用get的方式登录
* @param userName
* @param password
* @return 登录的状态
*/
public static String loginOfGet(String userName, String password) {
HttpClient client = null;
try {
client = new DefaultHttpClient();
String data = "username=" + userName + "&password=" + password;
HttpGet get = new HttpGet("http://10.0.2.2:8080/ServerItheima/servlet/LoginServlet?" + data);
HttpResponse respOnse= client.execute(get);
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode == 200) {
InputStream is = response.getEntity().getContent();
String text = getStringFromInputStream(is);
return text;
} else {
Log.i(TAG, "请求失败: " + statusCode);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(client != null) {
client.getConnectionManager().shutdown();
}
}
return null;
}
/**
* 根据流返回一个字符串信息
* @param is
* @return
* @throws IOException
*/
private static String getStringFromInputStream(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
is.close();
String html = baos.toString();
baos.close();
return html;
}
3.向服务器提交数据:
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
private EditText etUserName;
private EditText etPassword;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etUserName = (EditText) findViewById(R.id.et_username);
etPassword = (EditText) findViewById(R.id.et_password);
}
/**
* 使用httpClient方式提交get请求
* @param v
*/
public void doHttpClientOfGet(View v) {
Log.i(TAG, "doHttpClientOfGet");
final String userName = etUserName.getText().toString();
final String password = etPassword.getText().toString();
new Thread(new Runnable() {
@Override
public void run() {
final String state = NetUtils2.loginOfGet(userName, password);
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, state, 0).show();
}
});
}}).start();
}
/**
* 使用httpClient方式提交post请求
* @param v
*/
public void doHttpClientOfPost(View v) {
Log.i(TAG, "doHttpClientOfPost");
final String userName = etUserName.getText().toString();
final String password = etPassword.getText().toString();
new Thread(new Runnable() {
@Override
public void run() {
final String state = NetUtils2.loginOfPost(userName, password);
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, state, 0).show();
}
});
}
}).start();
}
public void doGet(View v) {
final String userName = etUserName.getText().toString();
final String password = etPassword.getText().toString();
new Thread(
new Runnable() {
@Override
public void run() {
final String state = NetUtils.loginOfGet(userName, password);
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, state, 0).show();
}
});
}
}).start();
}
public void doPost(View v) {
final String userName = etUserName.getText().toString();
final String password = etPassword.getText().toString();
new Thread(new Runnable() {
@Override
public void run() {
final String state = NetUtils.loginOfPost(userName, password);
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, state, 0).show();
}
});
}
}).start();
}
4.使用第三方开源框架AsyncHttpClient(android-async-http-master)实现:
public class MainActivity2 extends Activity {
protected static final String TAG = "MainActivity2";
private EditText etUserName;
private EditText etPassword;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etUserName = (EditText) findViewById(R.id.et_username);
etPassword = (EditText) findViewById(R.id.et_password);
}
public void doGet(View v) {
final String userName = etUserName.getText().toString();
final String password = etPassword.getText().toString();
AsyncHttpClient client = new AsyncHttpClient();
String data = "username=" + URLEncoder.encode(userName) + "&password=" + URLEncoder.encode(password);
client.get("http://10.0.2.2:8080/ServerItheima/servlet/LoginServlet?" + data, new MyResponseHandler());
}
public void doPost(View v) {
final String userName = etUserName.getText().toString();
final String password = etPassword.getText().toString();
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("username", userName);
params.put("password", password);
client.post("http://10.0.2.2:8080/ServerItheima/servlet/LoginServlet",
params,
new MyResponseHandler());
}
class MyResponseHandler extends AsyncHttpResponseHandler {
@Override
public void onSuccess(int statusCode, Header[] headers,
byte[] responseBody) {
Toast.makeText(MainActivity2.this,
"成功: statusCode: " + statusCode + ", body: " + new String(responseBody),
0).show();
}
@Override
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) {
Toast.makeText(MainActivity2.this, "失败: statusCode: " + statusCode, 0).show();
}
}
2.服务器端代码:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
username = new String(username.getBytes("iso8859-1"), "utf-8");
password = new String(password.getBytes("iso8859-1"), "utf-8");
System.out.println("姓名: " + username);
System.out.println("密码: " + password);
if("lisi".equals(username) && "123".equals(password)) {
response.getOutputStream().write("登录成功".getBytes("utf-8"));
} else {
response.getOutputStream().write("登录失败".getBytes("utf-8"));
}