您的位置:首页 > 移动开发 > Android开发

Android请求服务器常用方式

2014-08-26 10:15 357 查看
最近在学习Android和服务器的请求,觉得有必要记录一下,防止自己忘记

Andriod和服务器通信,一般使用Http协议,Http协议请求方式包括:GET、POST这两种方式;还有就是使用webservice的方式(不再这篇范围之类)

在服务器端,使用servelt来接受传递过来的参数:

public class LoginServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String name=request.getParameter("name");
String pwd=request.getParameter("pwd");

if("admin".equals(name)&&"admin".equals(pwd)){
response.getOutputStream().write("login success".getBytes());
}else{
response.getOutputStream().write("login error".getBytes());
}
}
}


下面开始使用HTTP的Get方式编写代码和服务器请求:

req_btn_get.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
final String name = req_et_name.getText().toString().trim();
final String pwd = req_et_pwd.getText().toString().trim();
// 用一个线程来登录
new Thread() {
@Override
public void run() {
final String resu = RequestServerService.RequestGet(
name, pwd);
if (resu != null) {
runOnUiThread(new Runnable() {

@Override
public void run() {
Toast.makeText(RequestServerActivity.this,
resu, 0).show();
}
});
} else {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(RequestServerActivity.this,
"请求失败", 0).show();
}
});
}
};
}.start();
}
});其中使用到了RequestServerService这个类的RequestGet方法,这个类是是一个工具类,主要是把封装请求,代码如下:
public static String RequestGet(String name, String pwd) {
String path = "http://192.168.4.111:8080/AndroidServer/server?name="
+ name + "&pwd=" + pwd;
try {
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setConnectTimeout(5000);
connection.setRequestMethod("GET");
if (connection.getResponseCode() == 200) {
InputStream is = connection.getInputStream();
String result = StreamUtils.readInputStream(is);
return result;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}Get方式请求服务器有一个不爽的地方是,如果请求的参数多了就需要不断的拼凑在请求URL的后面,很容易出现问题,可以使用POST的方式请求服务器,代码如下:
public static String RequestPost(String name, String pwd) {
String path = "http://192.168.4.111:8080/AndroidServer/server";
String data = "name=" + name + "&pwd=" + pwd;
try {
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setReadTimeout(5000);
connection.setRequestMethod("POST");
// 设置POST必须的属性
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", data.length() + "");
// 把数据写给服务器
connection.setDoInput(true);
OutputStream os = connection.getOutputStream();
os.write(data.getBytes());
if (connection.getResponseCode() == 200) {
InputStream is = connection.getInputStream();
String result = StreamUtils.readInputStream(is);
return result;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}细心的一定发现还是用了一个工具类StreamUtils,这个类主要就是把的到的inputStream请求解析出来,代码如下:
public static String readInputStream(InputStream is) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int leng = 0;
while ((leng = is.read(buffer)) != -1) {
baos.write(buffer, 0, leng);
}
is.close();
baos.close();
byte[] temp = baos.toByteArray();
String result = new String(temp);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return "解析失败";
}使用HTTP的POST或者GET都发现要写的代码很多,并且很多都是底层的,并未对其封装或者抽象。android系统本身对Apache的HttpClient进行了封装,直接调用即可代码结构如下:
GET方式如下:

public static String HttpClientGet(String name, String pwd) {
try {
String path = "http://192.168.4.111:8080/AndroidServer/server?name="
+ URLEncoder.encode(name)
+ "&pwd="
+ URLEncoder.encode(pwd);
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(path);
HttpResponse httpResponse = client.execute(get);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
InputStream is = httpResponse.getEntity().getContent();
String result = StreamUtils.readInputStream(is);
return result;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}POST方式如下:
public static String HttpClientPost(String name, String pwd) {
try {
String path = "http://192.168.4.111:8080/AndroidServer/server";
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(path);
// 指定要提交的数据
List<NameValuePair> list = new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("name", name));
list.add(new BasicNameValuePair("pwd", pwd));
httpPost.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
HttpResponse httpResponse = client.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
InputStream is = httpResponse.getEntity().getContent();
String result = StreamUtils.readInputStream(is);
return result;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}写完代码之,发现虽然使用Apache的HttpClent,但是写代码好像还是很多。如果关注过Git的一定知道有AsyncHttp这个开源项目,这个项目是再一次对Apache的HttpClient进行封装,在代码编写上和理解上比较容易,代码结果如下:
AsyncHttp的GET方式请求:

final String name = req_et_name.getText().toString().trim();
final String pwd = req_et_pwd.getText().toString().trim();
String url="http://192.168.4.111:8080/AndroidServer/server";
AsyncHttpClient asyncHttpClient=new AsyncHttpClient();
RequestParams params=new RequestParams();
params.put("name", name);
params.put("pwd", pwd);
asyncHttpClient.get(url, new AsyncHttpResponseHandler() {

@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {

}

@Override
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) {

}
});POST也一样,只是变了请求方式。
总结:学习了请求各种方式之后发现,各种请求方式都有自身的优势,只是针对各种使用场景不同而已。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: