public class MainActivity extends Activity {
private EditText et_username,et_password;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_username = (EditText) findViewById(R.id.et_username);
et_password = (EditText) findViewById(R.id.et_password);
}
public void loginByGet(View view){
final String username = et_username.getText().toString().trim();
final String password = et_password.getText().toString().trim();
new Thread(){
public void run() {
try {
//打开浏览器
HttpClient client = new DefaultHttpClient();
//请求方式为get,输入地址
HttpGet get = new HttpGet("http://192.168.0.100/Server/servlet/LoginServlet?username="
+ URLEncoder.encode(username, "UTF-8")
+ "&password="
+ URLEncoder.encode(password, "UTF-8")) ;
//敲回车,得到浏览器响应
HttpResponse response = client.execute(get);
//得到响应码
int code = response.getStatusLine().getStatusCode();
if(code == 200){
InputStream is = response.getEntity().getContent();
String result = StreamUtils.toString(is);
//调用showToast的runOnUIThread方法
showToast(result);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}.start();
}
public void loginByPost(View view) {
final String username = et_username.getText().toString().trim();
final String password = et_password.getText().toString().trim();
new Thread(){
public void run() {
try {
//打开浏览器
HttpClient client = new DefaultHttpClient();
//请求方式为POST,输入地址
HttpPost post = new HttpPost("http://192.168.0.100/Server/servlet/LoginServlet");
//准备请求体
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
NameValuePair nameValuePair = new BasicNameValuePair("username", username);
NameValuePair nameValuePair2 = new BasicNameValuePair("password", password);
parameters.add(nameValuePair);
parameters.add(nameValuePair2);
//将集合对象转为实体对象
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters);
//将请求体传给post
post.setEntity(entity);
//敲回车,得到浏览器响应
HttpResponse response = client.execute(post);
//得到响应码
int code = response.getStatusLine().getStatusCode();
if(code == 200) {
InputStream is = response.getEntity().getContent();
String result = StreamUtils.toString(is);
showToast(result);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}.start();
}
private void showToast(final String result) {
// TODO Auto-generated method stub
runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, result, 0).show();
}
});
}
}
HttpClient发送网络请求
最新推荐文章于 2018-11-02 09:37:21 发布