1.通过get方式
URL 链接后加参数 username= "admin"&password="admin" 通过 Connection 获取返回结果
编码url参数时,尽量这样,"username="+URLEncoder.encode(username,"utf-8")+"&password="+URLEncoder.encode(password,"utf-8")而不是把他们整体编码,有时候会报错。
核心代码:
public class MainActivity extends Activity {
private EditText et_username;
private EditText et_password;
private String path="http://10.0.2.2:8080/WebForAndroid/login";
@Override
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);
Button bt_login=(Button) findViewById(R.id.bt_login);
bt_login.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
new Thread(){
@Override
public void run() {
String username=et_username.getText().toString();
String password=et_password.getText().toString();
try {
URL url=new URL(path+"?username="+username+"&password="+password);
HttpURLConnection connection=(HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(10000);
int respond=connection.getResponseCode();
if(respond==200)
{
InputStream is=connection.getInputStream();
String str=Utils.getStringFromStream(is);
toastShow(str);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
});
}
public void toastShow(final String str){
runOnUiThread(new Runnable(){
public void run() {
Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
}
});
}
}
一个工具类:
public class Utils {
public static String getStringFromStream(InputStream is) {
String str="";
Reader br=new InputStreamReader(is);
char[]buf=new char[1024];
int leng;
try {
while((leng=br.read(buf))>0){
str=str+new String(buf,0,leng);
}
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
若是参数中含有中文,应该提前进行编码,URLEncoder.encode(str,"utf-8");
Post:
需要加上两个请求头
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", ""+params.length());
public class MainActivity extends Activity {
private EditText et_username;
private EditText et_password;
private String path="http://10.0.2.2:8080/WebForAndroid/login";
@Override
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);
Button bt_login=(Button) findViewById(R.id.bt_login_post);
bt_login.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
new Thread(){
@Override
public void run() {
String username=et_username.getText().toString();
String password=et_password.getText().toString();
String params="username="+URLEncoder.encode(username,"utf-8")+"&password="+URLEncoder.encode(password,"utf-8");
try {
URL url=new URL(path);
HttpURLConnection connection=(HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setConnectTimeout(10000);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", ""+params.length());
connection.setDoOutput(true);
connection.getOutputStream().write(params.getBytes());
int respond=connection.getResponseCode();
if(respond==200)
{
InputStream is=connection.getInputStream();
String str=Utils.getStringFromStream(is);
toastShow(str);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
});
}
public void toastShow(final String str){
runOnUiThread(new Runnable(){
public void run() {
Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
}
});
}
}
3.Client方式
可以以 get/post 等方式提交
先是get方式
HttpClient client=new DefaultHttpClient();
HttpResponse response=client.execute(new HttpGet(path+"?"+params));
int respond=response.getStatusLine().getStatusCode();
if(respond==200)
{
String str=Utils.getStringFromStream(response.getEntity().getContent());
toastShow(str);
}
思路:获取DefaultHttpClient , 然后执行execute 方法 , 获取HttpResponse ,getStatusLine().getStatusCode() 获取返回码,然后getEntity().getContent() 获取从服务器返回的输入流。
然后post方式:
HttpClient client=new DefaultHttpClient();
HttpPost post=new HttpPost(path);
List<BasicNameValuePair>list=new ArrayList<BasicNameValuePair>();
BasicNameValuePair pair=new BasicNameValuePair("username",username);
list.add(pair);
BasicNameValuePair pair2=new BasicNameValuePair("password",password);
list.add(pair2);
HttpEntity entity=new UrlEncodedFormEntity(list);
post.setEntity(entity);
HttpResponse response=client.execute(post);
前面和get方式大相径庭,但post方式需要将参数巧妙的加入进来。
post->setEntity -> UrlEncodedFormEntity -> List<BasicNameValuePair> ->BasicNameValuePair 通过构造器将参数传进来。
4.使用开源项目android-async-http-1.4.8.jar(在实际项目中最为常用)
先是get方法
注意:应该在点击登陆后再获取参数信息,而不是在页面加载完毕就获取参数信息。
public class MainActivity extends Activity {
private EditText et_username;
private EditText et_password;
private String path="http://10.0.2.2:8080/WebForAndroid/login";
private String url;
@Override
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);
Button bt_login=(Button) findViewById(R.id.bt_login_post);
bt_login.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
url=path+"?"+"username="+et_username.getText().toString()+"&password="+et_password.getText().toString();
//获取AsyncHttpClient对象
//Async 异步的,表示代码会在子线程执行任务。
//sync 同步的,表示代码会在创建这个对象的线程中执行,不会开线程。
AsyncHttpClient client=new AsyncHttpClient();
//如果是get方式,则调用get方法,第一个参数,访问的地址
//第二个参数,处理http响应的回调对象 相应相关的内容通过两个方法 onsuccess onfailure
client.get(url, new MyHandler());
}
});
}
public void toastShow(final String str){
runOnUiThread(new Runnable(){
public void run() {
Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
}
});
}
private class MyHandler extends AsyncHttpResponseHandler{
@Override
public void onFailure(int arg0, Header[] arg1, byte[] arg2,
Throwable arg3) {
toastShow("登录失败");
}
//参数1 表返回码,参数2表返回头,参数3表返回内容的字节数组
@Override
public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
if(arg0==200){
String result="";
try {
result = new String(arg2,"utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
toastShow(result);
}
}
}
}
然后是post方法:
AsyncHttpClient client=new AsyncHttpClient();
HashMap<String,String> map=new HashMap<String,String>();
map.put("username", et_username.getText().toString());
map.put("password", et_password.getText().toString());
RequestParams params=new RequestParams(map);
//如果是post方式,则调用post方法,第一个参数,访问的地址
//第二个参数,传入的参数
client.post(path, params, new MyHandler());