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);
/**
* 执行任务在主线程中
*
* new Runnable():如果是当前线程则立即执行,如果不是,则将这个线程加到主线程中,去执行
* 也就是把主线程的任务 在子线程中 执行
*
*
*/
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, state, 0).show();
}
});
}
}).start();
}
}
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/ServerItheima28/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/ServerItheima28/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();
}
}
}
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/ServerItheima28/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 {
/**
* get 提交中文时,要进行 url 编码
*/
String data = "username=" + URLEncoder.encode(userName,"UTF-8")
+ "&password=" + URLEncoder.encode(password,"UTF-8");
URL url = new URL("http://10.0.2.2:8080/ServerItheima28/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;
}
}
/***
* httpClient 请求数据
* @param name
* @param password
* @return
*/
public static String loginByClientGet(String name,String password) {
HttpClient client = new DefaultHttpClient();
String path = "http:www.baidu.com?username="+URLEncoder.encode(name)+"&password="+URLEncoder.encode(password);
HttpGet httpGet= new HttpGet(path);
try {
HttpResponse response = client.execute(httpGet);
int code = response.getStatusLine().getStatusCode();
if(code == 200){
InputStream iStream = response.getEntity().getContent();
String text = getStringFromInputStream(iStream);
return text;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String loginByClientPost(String name,String password) {
try {
HttpClient client = new DefaultHttpClient();
String path = "http:www.baidu.com";
HttpPost httpPost= new HttpPost(path);
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("username", "zhang"));
parameters.add(new BasicNameValuePair("password", "zhang"));
httpPost.setEntity(new UrlEncodedFormEntity(parameters,"utf-8"));
HttpResponse response = client.execute(httpPost);
int code = response.getStatusLine().getStatusCode();
if(code == 200){
InputStream iStream = response.getEntity().getContent();
String text = getStringFromInputStream(iStream);
return text;
}
}catch(Exception exception){
return null;
}
return null;
}