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

Android--向服务器提交数据的两种方法Post和Get

2014-12-22 22:21 579 查看
有些方法用的不是很好,希望大家多多指正

public class MainActivity extends ActionBarActivity {
EditText et_name;
EditText et_password;
Button b_post;
Button b_get;
URL url;
HttpURLConnection conn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_name = (EditText)findViewById(R.id.et_name);
et_password = (EditText)findViewById(R.id.et_password);
b_get = (Button)findViewById(R.id.b_get);
b_post = (Button)findViewById(R.id.b_post);
}
public void clik(final View view){
new Thread(){
@Override
public void run() {
super.run();
String <span style="font-family:System;">name</span> = et_name.getText().toString();
String password = et_password.getText().toString();
if (name.isEmpty()|| password.isEmpty()){
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this,"用户名或密码不能为空",Toast.LENGTH_SHORT).show();
}
});
return;
}
final String s;
if (view.getId() == R.id.b_get){
s= d<span style="font-family:System;">oGet(name ,password);</span>
}else {
s= do<span style="font-family:System;">Post(name ,password);</span>
}
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this,s,Toast.LENGTH_SHORT).show();
}
});
}
}.start();
}
public String doPost(String name,String password){
String u = "http://192.168.2.3:8080/Web/TestServlet";
String date = "name=" + name + "&password=" + password;
try {
url = new URL(u);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(5000);
conn.setDoOutput(true);
conn.setDoInput(true);
PrintWriter pw = new PrintWriter(conn.getOutputStream());
pw.print(date);
pw.flush();
int code = conn.getResponseCode();
System.out.println(code);
if (code == 200){
InputStream is = conn.getInputStream();
String s = new BufferedReader(new InputStreamReader(is)).readLine();
System.out.println(s);
return s;
}else{
return "连接失败...";
}

} catch (Exception e) {
e.printStackTrace();
return "连接失败...";
}
}
public String doGet(String name,String password){
String u = "http://192.168.2.3:8080/Web/<span style="font-family: Arial, Helvetica, sans-serif;">TestServlet</span>";
String date = "?name=" + name + "&password=" + password;
try {
url = new URL(u + date);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
int code = conn.getResponseCode();
if (code == 200){
InputStream is = conn.getInputStream();
String s = new BufferedReader(new InputStreamReader(is)).readLine();
System.out.println(s);
return s;
}else{
return "连接失败...";
}
} catch (Exception e) {
e.printStackTrace();
return "连接失败...";
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: