Android Http 客户端编程之GET
说起Http编程,不尽然想起GET和POST两种请求方式,本文以简洁明了的的步骤和说明,将Android中常用的Http编程的方式列举出来,给刚刚在Android路上起步的奋斗者参考和指引,希望快速上手应用Android Http编程的同仁可以先绕过下面一段话。
做一件事之前,我们是否能驻足想一下要做这件事,我们需要做哪些工作,然后在经验中积累出模板思路和步骤,在程序界通常用设计模式来概括这些工作良好的解决方案。有了这些总结积累,这样我们就能举一反三,面对新的问题不再 无所适从,这是一个优秀程序员必须养成的能力,所以每个爱好编程的同仁都有责任让自己成为一个优秀的程序员程序员。
Android Http 客户端编程设计模式(步骤):
1.网络权限:添加INTERNET用户权限。
2.UI设计:设计用户界面。
3.发出请求:客户端提交HTTP请求,提交数据,切记不能在UI线程完成。
4.接收响应:接收服务器端的响应,获取服务器返回数据。
5.UI更新:客户端业务处理,更新UI。
此模式是我初学Android给自己总结的一套模式,这样能够帮助我在涉及到HTTP编程的时候能够编写出良好工作的代码,欢迎同仁给出宝贵的意见。下面是根据这套模式实现的HTTP编程实践。
1.网络权限,添加用户权限:
<uses-permission android:name="android.permission.INTERNET"/>2.UI设计,登陆界面的UI,文本框*1+密码框*1+按钮*1,UI较为简单,布局文件内容略,这个之所以写成中文,后面会有一个中文乱码的问题,为了简化篇幅,此处EditText和Button的Text直接写好,这是一个很不好的编码习惯,强烈建议实际中抽离出来,在string.xml中定义,以此为鉴。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/et_userName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入用户名"
android:text="袁慎建" />
<EditText
android:id="@+id/et_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入密码"
android:inputType="textPassword"
android:text="000" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="loginByGet"
android:text="GET登陆" />
</LinearLayout>3.发出请求:编写客户端HTTP请求,并提交数据,中文用户名需要进行URL编码,见代码。(此步骤不能在UI线程进行)
4.接收响应:接收服务器端的响应,请求成功后获取响应输入流。(此步骤不能在UI线程进行)
public static final String URL_PREFIX = "http://191.168.2.177:8080/LoginServer/LoginServlet";
/**
* Get方式提交请求,此方法只能在非UI线程进行调用
*
* @param userName
* @param password
* @return
*/
public static String loginByGet(String userName, String password) {
try {
// 对中文进行编码
String path = URL_PREFIX + "?user="
+ URLEncoder.encode(userName, "UTF-8") + "&pass="
+ URLEncoder.encode(password, "UTF-8");
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
int code = conn.getResponseCode();
if (code == 200) {
InputStream is = conn.getInputStream();
return readStream(is);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 读取流中数据
*
* @param is
* @return
*/
public static String readStream(InputStream is) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] values = new byte[1024];
try {
try {
int length = 0;
while ((length = is.read(values)) != -1) {
baos.write(values, 0, length);
}
return new String(baos.toByteArray());
} finally {
if (baos != null) {
baos.close();
}
if (is != null) {
is.close();
}
}
} catch (IOException e) {
e.printStackTrace();
return "解析失败";
}
}
5.UI更新:解析服务器响应输入流数据后,将数据内容Toast显示出来,Android中Activity类中的runOnUiThread方法,适当使用可以简化Handler的编程。 public void loginByGet(View view) {
final String userName = etUserName.getText().toString();
final String password = etPassword.getText().toString();
if (TextUtils.isEmpty(userName) || TextUtils.isEmpty(password)) {
Toast.makeText(this, "用户名或密码不能为空", Toast.LENGTH_LONG).show();
return;
}
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(new Runnable() {
@Override
public void run() {
// 调用LoginService中的方法
final String result = LoginService.loginByGet(userName,
password);
/*
* 利用这个方法可以方便更新UI,如果当前线程是ui线程,会立即执行,否则会被放到UI线程的事件队列中 Runs the
* specified action on the UI thread. If the current thread is
* the UI thread, then the action is executed immediately. If
* the current thread is not the UI thread, the action is posted
* to the event queue of the UI thread.
*/
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),
result + "-------", Toast.LENGTH_LONG).show();
}
});
}
});
executorService.shutdown();
}通过这篇文章,有没有引发你对HTTP编程的一些思考和总结,当我们要实现HTTP客户端的时候,只需要记住简单的设计模式中的五个步骤,这只是一个简单的GET请求的例子,后面会继续退出此设计模式下的POST请求,以及HTTP一些框架的使用,敬请期待。
文章来源:http://blog.csdn.net/ysjian_pingcx/article/details/25915047
原文:http://blog.csdn.net/long7181226/article/details/25985711