get提交代码
1 import java.io.InputStream;
2 import java.net.HttpURLConnection;
3 import java.net.MalformedURLException;
4 import java.net.URL;
5 import java.net.URLDecoder;
6 import java.net.URLEncoder;
7
8 import com.itheima.htmlviewer.utils.Utils;
9
10 import android.os.Bundle;
11 import android.os.Handler;
12 import android.os.Message;
13 import android.app.Activity;
14 import android.view.Menu;
15 import android.view.View;
16 import android.widget.EditText;
17 import android.widget.Toast;
18
19 public class MainActivity
extends Activity {
20
21 @Override
22 protected void onCreate(Bundle savedInstanceState) {
23 super.onCreate(savedInstanceState);
24 setContentView(R.layout.activity_main);
25 }
26
27 Handler handler =
new Handler(){
28 public void handleMessage(android.os.Message msg) {
29 Toast.makeText(MainActivity.
this, (String)msg.obj, 0
).show();
30 }
31 };
32
33 public void click(View v){
34 EditText et_name =
(EditText) findViewById(R.id.et_name);
35 EditText et_pass =
(EditText) findViewById(R.id.et_pass);
36
37 final String name =
et_name.getText().toString();
38 final String pass =
et_pass.getText().toString();
39
40 Thread t =
new Thread(){
41 @Override
42 public void run() {
43 //提交的数据需要经过url编码,英文和数字编码后不变
44 @SuppressWarnings("deprecation"
)
45 String path = "http://192.168.13.13/Web2/servlet/LoginServlet?name=" + URLEncoder.encode(name) + "&pass=" +
pass;
46
47 try {
48 URL url =
new URL(path);
49 HttpURLConnection conn =
(HttpURLConnection) url.openConnection();
50 conn.setRequestMethod("GET"
);
51 conn.setConnectTimeout(5000
);
52 conn.setReadTimeout(5000
);
53
54 if(conn.getResponseCode() == 200
){
55 InputStream is =
conn.getInputStream();
56 String text =
Utils.getTextFromStream(is);
57
58 Message msg =
handler.obtainMessage();
59 msg.obj =
text;
60 handler.sendMessage(msg);
61 }
62 }
catch (Exception e) {
63 // TODO Auto-generated catch block
64 e.printStackTrace();
65 }
66 }
67 };
68 t.start();
69
70
71
72 }
73
74 }
util
1 import java.io.ByteArrayOutputStream;
2 import java.io.IOException;
3 import java.io.InputStream;
4
5 public class Utils {
6
7 public static String getTextFromStream(InputStream is){
8
9 byte[] b =
new byte[1024
];
10 int len = 0
;
11 //创建字节数组输出流,读取输入流的文本数据时,同步把数据写入数组输出流
12 ByteArrayOutputStream bos =
new ByteArrayOutputStream();
13 try {
14 while((len = is.read(b)) != -1
){
15 bos.write(b, 0
, len);
16 }
17 //把字节数组输出流里的数据转换成字节数组
18 String text =
new String(bos.toByteArray());
19 return text;
20 }
catch (IOException e) {
21 // TODO Auto-generated catch block
22 e.printStackTrace();
23 }
24 return null;
25 }
26 }
转载于:https://www.cnblogs.com/wangying222/p/5603048.html
相关资源:以GET或者POST方式向网页提交参数