Android中提交数据的三种方式
2017-03-04 20:03
369 查看
[java] view
plain copy
/*该类演示了四种方法提交数据到服务器,并将服务器解析后的数据以字符串的形式返回*/
public class LoginService {
/**
*
* @param username
* @param password
* @return
*/
public static String loginByGet(String username,String password){
try {
//提交数据到服务器
//拼装路径
String path = "http://192.168.1.100/Web/servlet/LoginServlet?username="
+ URLEncoder.encode(username,"UTF-8") + "&password=" + URLEncoder.encode(password,"UTF-8");
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();//打开连接
conn.setRequestMethod("GET");//设置请求方式为get
conn.setConnectTimeout(5000);//设置连接超时时间为5秒
int code = conn.getResponseCode();//获得请求码
if(code == 200){
InputStream is = conn.getInputStream();
String text = StreamTools.readInputStream(is);
return text;
}else{
return null;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
*
* @param username
* @param password
* @return
*/
public static String loginByPost(String username,String password){
try {
//提交数据到服务器
//拼装路径
String path = "http://192.168.1.100/Web/servlet/LoginServlet";
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();//打开连接
conn.setRequestMethod("POST");//设置请求方式为get
conn.setConnectTimeout(5000);//设置连接超时时间为5秒
//准备数据
String data = "username="+ URLEncoder.encode(username,"UTF-8") + "&password=" + URLEncoder.encode(password,"UTF-8");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", data.length()+"");
//post的方式实际上是浏览器把数据写给了服务器
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
os.write(data.getBytes());
int code = conn.getResponseCode();//获得请求码
if(code == 200){
InputStream is = conn.getInputStream();
String text = StreamTools.readInputStream(is);
return text;
}else{
return null;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 采用httpclient get提交数据
* @param username
* @param password
* @return
*/
public static String loginByClientGet(String username,String password){
try {
//1.打开一个浏览器
HttpClient client = new DefaultHttpClient();
//2.输入地址
String path = "http://192.168.1.100/Web/servlet/LoginServlet?username="
+ URLEncoder.encode(username)
+ "&password="
+ URLEncoder.encode(password);
HttpGet httpGet = new HttpGet(path);
//3.敲回车
HttpResponse response = client.execute(httpGet);
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
InputStream is = response.getEntity().getContent();
String text = StreamTools.readInputStream(is);
return text;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 采用httpclient post提交数据
* @param username
* @param password
* @return
*/
public static String loginByClientPost(String username,String password){
try {
//1.打开一个浏览器
HttpClient client = new DefaultHttpClient();
//2.输入地址
String path = "http://192.168.1.100/Web/servlet/LoginServlet";
HttpPost httpPost = new HttpPost(path);
//指定要提交的数据实体
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("username", username));
parameters.add(new BasicNameValuePair("password", password));
httpPost.setEntity(new UrlEncodedFormEntity(parameters,"UTF-8"));
//3.敲回车
HttpResponse response = client.execute(httpPost);
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
InputStream is = response.getEntity().getContent();
String text = StreamTools.readInputStream(is);
return text;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
将输入流转换为字符串的工具类StreamTools代码如下:
[java] view
plain copy
public class StreamTools {
/**
* 把输入流的内容转化成字符串
* @param is
* @return
* @throws IOException
*/
public static String readInputStream(InputStream is){
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
int len = 0;
byte[] buffer = new byte[1024];
while((len=is.read(buffer))!=-1){
stream.write(buffer, 0, len);
}
is.close();
stream.close();
byte[] result = stream.toByteArray();
//试着解析 result 里面的字符串
String temp = new String(result);
return temp;
} catch (Exception e) {
e.printStackTrace();
return "获取失败";
}
}
}
在主界面测试是否成功提交的代码如下:
[java] view
plain copy
public class MainActivity extends Activity {
private EditText et_username;
private EditText et_password;
@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);
}
public void click1(View view){
final String username = et_username.getText().toString().trim();
final String password = et_password.getText().toString().trim();
new Thread(){
public void run() {
final String result = LoginService.loginByGet(username, password);
if(result!=null){
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
}
});
}else{
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "请求失败...", Toast.LENGTH_SHORT).show();
}
});
}
};
}.start();
}
public void click2(View view){
final String username = et_username.getText().toString().trim();
final String password = et_password.getText().toString().trim();
new Thread(){
public void run() {
final String result = LoginService.loginByGet(username, password);
if(result!=null){
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
}
});
}else{
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "请求失败...", Toast.LENGTH_SHORT).show();
}
});
}
};
}.start();
}
public void click3(View view){
final String username = et_username.getText().toString().trim();
final String password = et_password.getText().toString().trim();
new Thread(){
public void run() {
final String result = LoginService.loginByClientGet(username, password);
if(result!=null){
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
}
});
}else{
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "请求失败...", Toast.LENGTH_SHORT).show();
}
});
}
};
}.start();
}
public void click4(View view){
final String username = et_username.getText().toString().trim();
final String password = et_password.getText().toString().trim();
new Thread(){
public void run() {
final String result = LoginService.loginByClientPost(username, password);
if(result!=null){
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
}
});
}else{
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "请求失败...", Toast.LENGTH_SHORT).show();
}
});
}
};
}.start();
}
public void click5(View view){
final String username = et_username.getText().toString().trim();
final String password = et_password.getText().toString().trim();
AsyncHttpClient client = new AsyncHttpClient();
String url = "http://127.0.0.1:80/Web/servlet/LoginServlet";
RequestParams params = new RequestParams();
params.put("username", username);
params.put("password", password);
client.post(url, params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Toast.makeText(MainActivity.this, "请求失败..."+new String(responseBody), 0).show();
}
@Override
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) {
Toast.makeText(MainActivity.this, "请求失败..."+new String(responseBody), 0).show();
}
});
}
}
使用开源项目AsnycHttpclient提交数据
plain copy
/*该类演示了四种方法提交数据到服务器,并将服务器解析后的数据以字符串的形式返回*/
public class LoginService {
/**
*
* @param username
* @param password
* @return
*/
public static String loginByGet(String username,String password){
try {
//提交数据到服务器
//拼装路径
String path = "http://192.168.1.100/Web/servlet/LoginServlet?username="
+ URLEncoder.encode(username,"UTF-8") + "&password=" + URLEncoder.encode(password,"UTF-8");
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();//打开连接
conn.setRequestMethod("GET");//设置请求方式为get
conn.setConnectTimeout(5000);//设置连接超时时间为5秒
int code = conn.getResponseCode();//获得请求码
if(code == 200){
InputStream is = conn.getInputStream();
String text = StreamTools.readInputStream(is);
return text;
}else{
return null;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
*
* @param username
* @param password
* @return
*/
public static String loginByPost(String username,String password){
try {
//提交数据到服务器
//拼装路径
String path = "http://192.168.1.100/Web/servlet/LoginServlet";
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();//打开连接
conn.setRequestMethod("POST");//设置请求方式为get
conn.setConnectTimeout(5000);//设置连接超时时间为5秒
//准备数据
String data = "username="+ URLEncoder.encode(username,"UTF-8") + "&password=" + URLEncoder.encode(password,"UTF-8");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", data.length()+"");
//post的方式实际上是浏览器把数据写给了服务器
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
os.write(data.getBytes());
int code = conn.getResponseCode();//获得请求码
if(code == 200){
InputStream is = conn.getInputStream();
String text = StreamTools.readInputStream(is);
return text;
}else{
return null;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 采用httpclient get提交数据
* @param username
* @param password
* @return
*/
public static String loginByClientGet(String username,String password){
try {
//1.打开一个浏览器
HttpClient client = new DefaultHttpClient();
//2.输入地址
String path = "http://192.168.1.100/Web/servlet/LoginServlet?username="
+ URLEncoder.encode(username)
+ "&password="
+ URLEncoder.encode(password);
HttpGet httpGet = new HttpGet(path);
//3.敲回车
HttpResponse response = client.execute(httpGet);
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
InputStream is = response.getEntity().getContent();
String text = StreamTools.readInputStream(is);
return text;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 采用httpclient post提交数据
* @param username
* @param password
* @return
*/
public static String loginByClientPost(String username,String password){
try {
//1.打开一个浏览器
HttpClient client = new DefaultHttpClient();
//2.输入地址
String path = "http://192.168.1.100/Web/servlet/LoginServlet";
HttpPost httpPost = new HttpPost(path);
//指定要提交的数据实体
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("username", username));
parameters.add(new BasicNameValuePair("password", password));
httpPost.setEntity(new UrlEncodedFormEntity(parameters,"UTF-8"));
//3.敲回车
HttpResponse response = client.execute(httpPost);
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
InputStream is = response.getEntity().getContent();
String text = StreamTools.readInputStream(is);
return text;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
将输入流转换为字符串的工具类StreamTools代码如下:
[java] view
plain copy
public class StreamTools {
/**
* 把输入流的内容转化成字符串
* @param is
* @return
* @throws IOException
*/
public static String readInputStream(InputStream is){
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
int len = 0;
byte[] buffer = new byte[1024];
while((len=is.read(buffer))!=-1){
stream.write(buffer, 0, len);
}
is.close();
stream.close();
byte[] result = stream.toByteArray();
//试着解析 result 里面的字符串
String temp = new String(result);
return temp;
} catch (Exception e) {
e.printStackTrace();
return "获取失败";
}
}
}
在主界面测试是否成功提交的代码如下:
[java] view
plain copy
public class MainActivity extends Activity {
private EditText et_username;
private EditText et_password;
@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);
}
public void click1(View view){
final String username = et_username.getText().toString().trim();
final String password = et_password.getText().toString().trim();
new Thread(){
public void run() {
final String result = LoginService.loginByGet(username, password);
if(result!=null){
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
}
});
}else{
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "请求失败...", Toast.LENGTH_SHORT).show();
}
});
}
};
}.start();
}
public void click2(View view){
final String username = et_username.getText().toString().trim();
final String password = et_password.getText().toString().trim();
new Thread(){
public void run() {
final String result = LoginService.loginByGet(username, password);
if(result!=null){
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
}
});
}else{
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "请求失败...", Toast.LENGTH_SHORT).show();
}
});
}
};
}.start();
}
public void click3(View view){
final String username = et_username.getText().toString().trim();
final String password = et_password.getText().toString().trim();
new Thread(){
public void run() {
final String result = LoginService.loginByClientGet(username, password);
if(result!=null){
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
}
});
}else{
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "请求失败...", Toast.LENGTH_SHORT).show();
}
});
}
};
}.start();
}
public void click4(View view){
final String username = et_username.getText().toString().trim();
final String password = et_password.getText().toString().trim();
new Thread(){
public void run() {
final String result = LoginService.loginByClientPost(username, password);
if(result!=null){
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
}
});
}else{
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "请求失败...", Toast.LENGTH_SHORT).show();
}
});
}
};
}.start();
}
public void click5(View view){
final String username = et_username.getText().toString().trim();
final String password = et_password.getText().toString().trim();
AsyncHttpClient client = new AsyncHttpClient();
String url = "http://127.0.0.1:80/Web/servlet/LoginServlet";
RequestParams params = new RequestParams();
params.put("username", username);
params.put("password", password);
client.post(url, params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Toast.makeText(MainActivity.this, "请求失败..."+new String(responseBody), 0).show();
}
@Override
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) {
Toast.makeText(MainActivity.this, "请求失败..."+new String(responseBody), 0).show();
}
});
}
}
使用开源项目AsnycHttpclient提交数据
项目的官方网站:
http://loopj.com/android-async-http/,对应的github地址:https://github.com/loopj/android-async-http
我这里简要介绍下:它是专门针对Android在Apache的HttpClient基础上构建的异步的callback-based
http client。所有的请求
全在UI线程之外发生,而callback发生在创建它的线程中,应用了Android的Handler发送消息机制。你也可以把AsyncHttpClient应用在
Service中或者后台线程中,库代码会自动识别出它所运行的context。它的feature包括:
1. 发送异步http请求,在匿名callback对象中处理response;
2. http请求发生在UI线程之外;
3. 内部采用线程池来处理并发请求;
4. GET/POST 参数构造,通过RequestParams类。
5. 内置多部分文件上传,不需要第三方库支持;
6. 流式Json上传,不需要额外的库;
7. 能处理环行和相对重定向;
8. 和你的app大小相比来说,库的size很小,所有的一切只有90kb;
9. 自动智能的请求重试机制在各种各样的移动连接环境中;
10. 自动的gzip响应解码;
11. 内置多种形式的响应解析,有原生的字节流,string,json对象,甚至可以将response写到文件中;
12. 永久的cookie保存,内部实现用的是Android的SharedPreferences;
13. 通过BaseJsonHttpResponseHandler和
各种json库集成;
14. 支持SAX解析器;
15. 支持各种语言和content编码,不仅仅是UTF-8。
大概翻译了下,这些只是大体的概览,具体的细节还得在使用过程中慢慢感受、学习。
接下来,带领大家看看应用android-async-http来写代码是个啥样子。简单来说你只需要3步,
1. 创建一个AsyncHttpClient;
2. (可选的)通过RequestParams对象设置请求参数;
3. 调用AsyncHttpClient的某个get方法,传递你需要的(成功和失败时)callback接口实现,一般都是匿名内部类
,实现了AsyncHttpResponseHandler,类库自己也提供了好些现成的response handler,你一般不需要自己创建一个。
来看看代码如何写:
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new AsyncHttpResponseHandler() {
@Override
public void onStart() {
// called before request is started
}
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
// called when response HTTP status is "200 OK"
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
}
@Override
public void onRetry(int retryNo) {
// called when request is retried
}
});
是不是很简洁,有没有被震撼到?反正我自己第一次看到的时候有种相见恨晚的感觉,这简直就是我日思夜想的方式啊!这里你只需要通过
匿名内部类的方式实现AsyncHttpResponseHandler,而且更棒的是你只需要override感兴趣的方法,比如一般都是onSuccess和onFailure。
这个版本的get方法没有为请求传递任何参数,当然你也可以通过RequestParams来传递各种参数,如下:
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("key", "value");
params.put("more", "data");
client.get("http://www.google.com", params, new
AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
System.out.println(response);
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.d("ERROR", error);
}
}
);
以上的例子是返回的response直接是原生字节流的情况,如果你需要把返回的结果当一个String对待,这时只需要匿名实现一个
TextHttpResponseHandler就行,其继承自AsyncHttpResponse,并将原生的字节流根据指定的encoding转化成了string对象,
代码如下:
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("key", "value");
params.put("more", "data");
client.get("http://www.google.com", params, new
TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, String response) {
System.out.println(response);
}
@Override
public void onFailure(int statusCode, Header[] headers, String responseBody, Throwable error) {
Log.d("ERROR", error);
}
}
);
同样的方式,你可以发送json请求,代码如下:
String url = "https://ajax.googleapis.com/ajax/services/search/images";
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("q", "android");
params.put("rsz", "8");
client.get(url, params, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
// Handle resulting parsed JSON response here
}
@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
// Handle resulting parsed JSON response here
}
});
看到了没,返回的response已经自动转化成JSONObject了,当然也支持JSONArray类型,override你需要的那个版本就行。
有了AsyncHttpClient,要实现这些功能是不是很简单呢?当然这里只是很初级的介绍和使用,剩下的还需要开发者自己参考官方
文档、源码(官方甚至提供了一个Sample使用的集合),在实际项目中实践。最后,强烈建议大家使用,是时候和冗长乏味的代码说
再见了。我一直是分析源码的,这次也不例外,实现上的关键代码我会在接下来的博客中专门介绍,敬请期待,enjoy。。。
相关文章推荐
- android 三种通过Http 协议 提交数据方式
- Android----用HTTP的get,post,HttpClient三种方式向web service提交文本数据
- Android之用HTTP的get,post,HttpClient三种方式向service提交文本数据
- Android之使用HTTP的get,post,HttpClient三种方式向服务器端提交文本数据
- Android之用HTTP的get,post,HttpClient三种方式向service提交文本数据
- Android网络数据之向服务器提交数据的三种方式(get+post+AsyncHttpClient)
- [Android开发]Android之使用HTTP的get,post,HttpClient三种方式向服务器端提交文本数据
- Android 用HttpClient 以Post方式提交数据并添加http头信息
- Android提交数据到服务器的两种方式四种方法
- Android中向web服务器提交数据的两种方式四种方法
- 使用get,post,httpclient三种方式向服务器提交文本数据
- ExtJS4.1:AJAX提交数据的三种方式,80%人都没用过第三种
- Android中的数据存取三种方式
- AJAX提交数据的三种方式,80%人都没用过第三种
- Android提交数据到服务器的两种方式四种方法
- Android提交数据到服务器的两种方式四种方法
- Android 使用三种方式获取网页(通过Post,Get进行表单的提交)
- android 通过get,post方式提交数据给服务器
- ExtJS4.2:AJAX提交数据的三种方式,80%人都没用过第三种
- Android 如何用HttpClient 以Post方式提交数据并添加http头信息