一,几种请求方式的解析
第一种:get请求方式请求数据
向服务器发索取数据的一种请求,get是获取信息,而不是修改信息,数据不会被修改,get请求的参数会跟在url(路径)后进行传递,请求的数据会附在URL之后,以?分割URL和传输数据,参数之间以&相连。
String url="http://192.168.1.117:8080/web2/servlet/LoginServlet?name="+URLEncoder.encode(name)+"&pass="+pass;
get传输的数据有大小限制,因为GET是通过url提交数据,不同的浏览器对URL的长度的限制是不同的。get请求的数据会被浏览器缓存起来,用户名和密码将明文出现在URL上,其他人可以查到历史浏览记录,数据不太安全。
第二种:post请求方式请求数据
向服务器提交数据的一种请求,post请求则作为http消息的实际内容发送给web服务器,数据放置在HTMLHeader内提交,post没有限制提交数据,post比get更安全。
String path = "http://192.168.1.117:8080/web2/servlet/LoginServlet";
String data="name="+URLEncoder.encode(name)+"&pass="+pass;
HttpClient框架已经将handler对象封装好了,所以比get和post方式更方便
第三种:HttpClient框架请求数据
HttpClient框架把请求的方法封装成了一个框架
与get和post请求类似:只是使用的对象不同,HttpClient直接把get请求和post请求的方法进行了封装
HttpClient hc = new DefaultHttpClient();
HttpGet hg = new HttpGet(path);//get请求
HttpPost hp=new HttpPost(path);//post请求
第四种:异步HttpClient框架请求数据
异步HttpClient框架比HttpClient框架更简单,他是借助第三方工具jar包里封装好的对象和方法实现请求数据的
AsyncHttpClient ahc = new AsyncHttpClient();
ahc.get(url, new MyResponseHandler());
二,需要注意的事项
1,无论哪种请求方式都需要添加网络权限
2,路径的格式必须与服务器提供的完全保持一致,否则不能连接
3,如果字段名字写错会出现登陆失败的情况
4,不要忘记把路径传参添加到请求方法中。否则请求不了
5,只要出现一点问题,都不会请求成功,所以一定要细心
6,get请求和post请求的方法get和post必须大写
下面可以具体看一下源码:
1,get请求方式请求数据:
public class MainActivity extends Activity {
Handler handler=new Handler(){
public void handleMessage(Message msg) {
Toast.makeText(getApplicationContext(), (CharSequence) msg.obj, 0).show();
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void click(View v){
EditText et_name=(EditText) findViewById(R.id.et_name);
EditText et_pass=(EditText) findViewById(R.id.et_pass);
final String name=et_name.getText().toString().trim();
final String pass=et_pass.getText().toString().trim();
new Thread(){
public void run() {
String path="http://192.168.1.117:8080/web2/servlet/LoginServlet?name="+URLEncoder.encode(name)+"&pass="+pass;
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(3000);
conn.setConnectTimeout(3000);
conn.connect();
if(conn.getResponseCode()==200){
InputStream is = conn.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(is,"GBK"));
StringBuffer buffer = new StringBuffer();
String line="";
while((line=in.readLine())!=null){
buffer.append(line);
}
String text=buffer.toString();
Message msg = new Message();
msg.obj=text;
handler.sendMessage(msg);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}.start();
}
}
2,post请求方式请求数据
public class MainActivity extends Activity {
Handler handler=new Handler(){
public void handleMessage(Message msg) {
Toast.makeText(MainActivity.this, (String) msg.obj, 0).show();
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void click(View v){
EditText et_name=(EditText) findViewById(R.id.et_name);
EditText et_pass=(EditText) findViewById(R.id.et_pass);
final String name=et_name.getText().toString().trim();
final String pass=et_pass.getText().toString().trim();
new Thread(){
public void run() {
String path = "http://192.168.1.117:8080/web2/servlet/LoginServlet";
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setReadTimeout(3000);
conn.setConnectTimeout(3000);
String data="name="+URLEncoder.encode(name)+"&pass="+pass;
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", data.length()+"");
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
os.write(data.getBytes());
conn.connect();
if(conn.getResponseCode()==200){
InputStream is = conn.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(is,"GBK"));
StringBuffer buffer = new StringBuffer();
String line="";
while((line=in.readLine())!=null){
buffer.append(line);
}
String text=buffer.toString();
Message msg = handler.obtainMessage();
msg.obj=text;
handler.sendMessage(msg);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}.start();
}
}
3,HttpClient框架请求数据
public class MainActivity extends Activity {
Handler handler=new Handler(){
public void handleMessage(Message msg) {
Toast.makeText(getApplicationContext(), (CharSequence) msg.obj, 0).show();
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
HttpClient框架get请求方式
public void get(View v){
EditText et_name = (EditText) findViewById(R.id.et_name);
EditText et_pass = (EditText) findViewById(R.id.et_pass);
final String name = et_name.getText().toString();
final String pass = et_pass.getText().toString();
new Thread(){
public void run() {
String path= "http://192.168.1.117:8080/web2/servlet/LoginServlet?name=" + URLEncoder.encode(name) + "&pass=" + pass;
HttpClient hc = new DefaultHttpClient();
HttpGet hg = new HttpGet(path);
try {
HttpResponse hr = hc.execute(hg);
StatusLine sl = hr.getStatusLine();
if(sl.getStatusCode() == 200){
HttpEntity he = hr.getEntity();
InputStream is = he.getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(is,"GBK"));
StringBuffer buffer = new StringBuffer();
String line="";
while((line=in.readLine())!=null){
buffer.append(line);
}
String text=buffer.toString();
Message msg = new Message().obtain();
msg.obj=text;
handler.sendMessage(msg);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}.start();
}
HttpClient框架post请求方式
public void post(View v){
EditText et_name = (EditText) findViewById(R.id.et_name);
EditText et_pass = (EditText) findViewById(R.id.et_pass);
final String name = et_name.getText().toString();
final String pass = et_pass.getText().toString();
new Thread(){
public void run() {
String path="http://192.168.1.117:8080/web2/servlet/LoginServlet";
HttpClient hc=new DefaultHttpClient();
//不要忘了把path传入
HttpPost hp=new HttpPost(path);
BasicNameValuePair bnvp1=new BasicNameValuePair("name",name);
BasicNameValuePair bnvp2=new BasicNameValuePair("pass",pass);
List parameters=new ArrayList();
parameters.add(bnvp1);
parameters.add(bnvp2);
try {
UrlEncodedFormEntity entity=new UrlEncodedFormEntity(parameters,"utf-8");
hp.setEntity(entity);
HttpResponse hr = hc.execute(hp);
if(hr.getStatusLine().getStatusCode()==200){
InputStream is = hr.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(is,"GBK")) ;
StringBuffer buffer = new StringBuffer();
String line="";
while((line=in.readLine())!=null){
buffer.append(line);
}
String text=buffer.toString();
Message msg = handler.obtainMessage();
msg.obj=text;
handler.sendMessage(msg);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}.start();
}
}
4,异步HttpClient框架请求数据
先导入第三方工具包至src文件夹中
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void get(View v){
EditText et_name = (EditText) findViewById(R.id.et_name);
EditText et_pass = (EditText) findViewById(R.id.et_pass);
final String name = et_name.getText().toString();
final String pass = et_pass.getText().toString();
String url = "http://192.168.1.117:8080/web2/servlet/LoginServlet?name=" + URLEncoder.encode(name) + "&pass=" + pass;
AsyncHttpClient ahc = new AsyncHttpClient();
ahc.get(url, new MyResponseHandler());
}
public void post(View v){
EditText et_name = (EditText) findViewById(R.id.et_name);
EditText et_pass = (EditText) findViewById(R.id.et_pass);
final String name = et_name.getText().toString();
final String pass = et_pass.getText().toString();
String url = "http://192.168.1.117:8080/web2/servlet/LoginServlet";
AsyncHttpClient ahc = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.add("name", name);
params.add("pass", pass);
ahc.post(url, params, new MyResponseHandler());
}
class MyResponseHandler extends AsyncHttpResponseHandler{
public void onSuccess(int statusCode, Header[] headers,
byte[] responseBody) {
try {
Toast.makeText(MainActivity.this, new String(responseBody,"GBK"), 0).show();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) {
Toast.makeText(MainActivity.this, "请求失败", 0).show();
}
}
}