Android開發使用POST方式向伺服器請求和傳送資料
阿新 • • 發佈:2019-01-27
package com.wzw.submitdata.utils; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class NetUtil { /** * 使用GET訪問去訪問網路 * @param username * @param password * @return 伺服器返回的結果 */ public static String loginOfGet(String username,String password){ HttpURLConnection conn=null; try { String data="username="+username+"&password="+password; URL url=new URL("http://192.168.1.4:8080/AndroidServer/LoginServlet?"+data); conn=(HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(10000); conn.setReadTimeout(5000); conn.connect(); int code=conn.getResponseCode(); if(code==200){ InputStream is=conn.getInputStream(); String state=getStringFromInputStream(is); return state; } } catch (Exception e) { e.printStackTrace(); }finally{ if(conn!=null){ conn.disconnect(); } } return null; } /** * 使用POST訪問去訪問網路 * @param username * @param password * @return */ public static String LoginOfPost(String username,String password){ HttpURLConnection conn=null; try { URL url=new URL("http://192.168.1.4:8080/AndroidServer/LoginServlet"); conn=(HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setConnectTimeout(10000); conn.setReadTimeout(5000); conn.setDoOutput(true); //post請求的引數 String data="username="+username+"&password="+password; OutputStream out=conn.getOutputStream(); out.write(data.getBytes()); out.flush(); out.close(); conn.connect(); int code=conn.getResponseCode(); if(code==200){ InputStream is=conn.getInputStream(); String state=getStringFromInputStream(is); return state; } } catch (Exception e) { e.printStackTrace(); }finally{ if(conn!=null){ conn.disconnect(); } } return null; } /** * 根據輸入流返回一個字串 * @param is * @return * @throws Exception */ private static String getStringFromInputStream(InputStream is) throws Exception{ ByteArrayOutputStream baos=new ByteArrayOutputStream(); byte[] buff=new byte[1024]; int len=-1; while((len=is.read(buff))!=-1){ baos.write(buff, 0, len); } is.close(); String html=baos.toString(); baos.close(); return html; } }