首页 > 代码库 > 安卓下使用GET方式向服务器端提交数据
安卓下使用GET方式向服务器端提交数据
从客户端提交数据给服务器端:
使用get方式向服务器端提交数据,把参数组拼到了url地址的后面:
http://192.168.0.10:8080/web/servlet/LoginServlet
?username=123&password=123445
源码板块:
package com.itheima.qqlogin;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.itheima.htmlview.utils.StreamTools;
public class MainActivity extends Activity {
private static final int ERROR = 0;
private static final int FAILED = 1;
private static final int SUCCESS = 2;
private EditText et_qq;
private EditText et_pwd;
//1、在主线程中创建一个handler的成员变量:
private Handler handler = new Handler(){
public void handleMessage(Message msg) {
int what = msg.what;
switch (what) {
case 0:
Toast.makeText(MainActivity.this, "访问网络失败", 0).show();
break;
case 1:
Toast.makeText(MainActivity.this, "服务返回数据失败", 0).show();
break;
case 2:
String result = (String) msg.obj;
Toast.makeText(MainActivity.this, result, 0).show();
break;
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_qq = (EditText) findViewById(R.id.et_qq);
et_pwd = (EditText) findViewById(R.id.et_pwd);
}
public void login(View v) {
final String qq = et_qq.getText().toString().trim();
final String pwd = et_pwd.getText().toString().trim();
if (TextUtils.isEmpty(qq) || TextUtils.isEmpty(pwd)) {
Toast.makeText(this, "qq号码或者密码不能为空", 0).show();
return;
} else {
new Thread(){
public void run() {
try {
// 1、创建URL对象、打开HTTP类型的连接;
String path = "http://192.168.0.10:8080/web/servlet/LoginServlet?username="+qq+"&password="+pwd;
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
// 2、设置请求头信息:GET;
conn.setRequestMethod("GET");
// 设置连接的超时时间
conn.setConnectTimeout(3000);
// conn.setRequestProperty("Accept-Language", "zh-CN");
// 3、获取服务器端返回的响应数据,二进制的输入流;
int code = conn.getResponseCode();
if (code == 200) {
InputStream is = conn.getInputStream();
String result = StreamTools.readStream(is);
Message msg = Message.obtain();
//消息码,用来区分是在什么地方发送的消息
msg.what = SUCCESS;
msg.obj = result;
handler.sendMessage(msg);
}else{
//服务返回数据失败
Message msg = Message.obtain();
//msg.obj = "服务返回数据失败";
msg.what = FAILED;
handler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
//访问网络失败
Message msg = Message.obtain();
//msg.obj = "访问网络失败";
msg.what = ERROR;
handler.sendMessage(msg);
}
};
}.start();
}
}
}
本文出自 “想富卖切糕” 博客,请务必保留此出处http://dkpzjl.blog.51cto.com/9545260/1569869
安卓下使用GET方式向服务器端提交数据