post提交代码
1 public class MainActivity extends Activity { 2 3 @Override 4 protected void onCreate(Bundle savedInstanceState) { 5 super.onCreate(savedInstanceState); 6 setContentView(R.layout.activity_main); 7 } 8 9 Handler handler = new Handler(){ 10 public void handleMessage(android.os.Message msg) { 11 Toast.makeText(MainActivity.this, (String)msg.obj, 0).show(); 12 } 13 }; 14 15 public void click(View v){ 16 EditText et_name = (EditText) findViewById(R.id.et_name); 17 EditText et_pass = (EditText) findViewById(R.id.et_pass); 18 19 final String name = et_name.getText().toString(); 20 final String pass = et_pass.getText().toString(); 21 22 Thread t = new Thread(){ 23 @Override 24 public void run() { 25 //提交的数据需要经过url编码,英文和数字编码后不变 26 @SuppressWarnings("deprecation") 27 String path = "http://192.168.13.13/Web2/servlet/LoginServlet"; 28 29 try { 30 URL url = new URL(path); 31 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 32 conn.setRequestMethod("POST"); 33 conn.setConnectTimeout(5000); 34 conn.setReadTimeout(5000); 35 36 //拼接出要提交的数据的字符串 37 String data = "name=" + URLEncoder.encode(name) + "&pass=" + pass; 38 //添加post请求的两行属性 39 conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 40 conn.setRequestProperty("Content-Length", data.length() + ""); 41 42 //设置打开输出流 43 conn.setDoOutput(true); 44 //拿到输出流 45 OutputStream os = conn.getOutputStream(); 46 //使用输出流往服务器提交数据 47 os.write(data.getBytes()); 48 if(conn.getResponseCode() == 200){ 49 InputStream is = conn.getInputStream(); 50 String text = Utils.getTextFromStream(is); 51 52 Message msg = handler.obtainMessage(); 53 msg.obj = text; 54 handler.sendMessage(msg); 55 } 56 } catch (Exception e) { 57 // TODO Auto-generated catch block 58 e.printStackTrace(); 59 } 60 } 61 }; 62 t.start(); 63 64 65 66 } 67 68 }
utils
1 public class Utils { 2 3 public static String getTextFromStream(InputStream is){ 4 5 byte[] b = new byte[1024]; 6 int len = 0; 7 //创建字节数组输出流,读取输入流的文本数据时,同步把数据写入数组输出流 8 ByteArrayOutputStream bos = new ByteArrayOutputStream(); 9 try { 10 while((len = is.read(b)) != -1){ 11 bos.write(b, 0, len); 12 } 13 //把字节数组输出流里的数据转换成字节数组 14 String text = new String(bos.toByteArray()); 15 return text; 16 } catch (IOException e) { 17 // TODO Auto-generated catch block 18 e.printStackTrace(); 19 } 20 return null; 21 } 22 }
时间: 2024-10-31 10:33:53