httpURLConnection使用get方法發送少許請求參數數據到後臺,後臺到數據庫獲取數據。html
鏈接地址和參數:java
String name="唐靜姝";
String sex="女";
try {
//tomcat9版本不接收連接地址中的中文字符,須要進行編碼才能接收
name=URLEncoder.encode(name, "utf-8");
sex=URLEncoder.encode(sex, "utf-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//?號隔開地址和參數,參數和參數間用&鏈接
String Url=arg0[0]+"?name="+name+"&sex="+sex;sql
安卓端的主要部分代碼:數據庫
/** * * @author httpURLConnection的get方法獲取數據庫數據 * */ public class PersonGetActivity extends Activity{ TextView tv_name,tv_gender,tv_age,tv_hight; String URL="http://ly-and-tl.uicp.cn:42696/AndroidServer/HttpURLConnection"; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.item); init(); new TASK().execute(URL); } void init(){ tv_name=(TextView) findViewById(R.id.tv_name); tv_gender=(TextView) findViewById(R.id.tv_gender); tv_age=(TextView) findViewById(R.id.tv_age); tv_hight=(TextView) findViewById(R.id.tv_hight); } class TASK extends AsyncTask<String, Void, Person>{ @Override protected void onPostExecute(Person result) { // TODO Auto-generated method stub if(result!=null){ tv_name.setText(result.getName()); tv_gender.setText(result.getSex()); tv_age.setText(String.valueOf(result.getAge())); tv_hight.setText(String.valueOf(result.getHight())); } } @SuppressWarnings("finally") @Override protected Person doInBackground(String... arg0) { // TODO Auto-generated method stub Person person=null; //輸入參數的設置不一樣點 String name="唐靜姝"; String sex="女"; try { //tomcat9版本不接收連接地址中的中文字符,須要進行編碼才能接收 name=URLEncoder.encode(name, "utf-8"); sex=URLEncoder.encode(sex, "utf-8"); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //?號隔開地址和參數,參數和參數間用&鏈接 String Url=arg0[0]+"?name="+name+"&sex="+sex; String str=null; StringBuffer sb=new StringBuffer(); try { URL url=new URL(Url); HttpURLConnection httpconn=(HttpURLConnection) url.openConnection(); httpconn.setRequestMethod("GET"); httpconn.setReadTimeout(5000); //發送請求 InputStream inputStream=httpconn.getInputStream(); InputStreamReader inputReader=new InputStreamReader(inputStream); BufferedReader buff=new BufferedReader(inputReader); while((str=buff.readLine())!=null){ sb.append(str); } Gson gson=new Gson(); String ss=new String(sb); System.out.println(ss); person=gson.fromJson(ss, new TypeToken<Person>(){}.getType()); System.out.println(person.getName()); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ return person; } } } }
服務端的代碼:json
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO 自動生成的方法存根 //Request.getParameter()也能夠接收到安卓端的參數 String name=req.getParameter("name"); String sex=req.getParameter("sex"); Connection con=null; ResultSet result=null; PreparedStatement prep=null; String sql="select * from stu_info where name=? and sex=?"; StudentHealthJavaBean student=null; con=DataBaseConnection.getConnection(); if(con!=null) { try { prep=con.prepareStatement(sql); prep.setString(1, name); prep.setString(2, sex); result=prep.executeQuery(); if(result.next()) { student=new StudentHealthJavaBean(); student.setName(result.getString("name")); student.setAge(result.getInt("age")); student.setId(result.getString("id")); student.setSex(result.getString("sex")); student.setHight(result.getFloat("hight")); student.setWeight(result.getFloat("weight")); } Gson json=new Gson(); String str=json.toJson(student); resp.setCharacterEncoding("utf-8"); PrintWriter p=resp.getWriter(); p.println(str); DataBaseConnection.closeDatabaseConnection(con, prep, result); } catch (SQLException e) { // TODO 自動生成的 catch 塊 e.printStackTrace(); } } }
安卓端主要部分代碼顯示:數組
public class PersonPostActivity extends Activity{ TextView textView; String URL="http://ly-and-tl.uicp.cn:42696/AndroidServer/HttpURLConnection"; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView=(TextView) findViewById(R.id.textView); new TASK().execute(URL); } class TASK extends AsyncTask<String, Void,String>{ @Override protected void onPostExecute(String result) { // TODO Auto-generated method stub super.onPostExecute(result); textView.setText(result); } @SuppressWarnings("finally") protected String doInBackground(String... arg0) { //輸出手機屬性 Properties propertys=System.getProperties(); propertys.list(System.out); //找到其中的encoding看手機編碼 StringBuffer sb=new StringBuffer(); // TODO Auto-generated method stub //輸入參數的設置不一樣點 String name="俾路支"; String sex="男"; String id="13"; int age=25; float hight=165; float weight=98; //?號隔開地址和參數,參數和參數間用&鏈接 String Url=arg0[0]; //post和get的不一樣之處在這裏 String property="id="+id+"&name="+name+"&sex="+sex+"&age="+age+"&hight="+hight+"&weight="+weight; String str=null; try { URL url=new URL(Url); HttpURLConnection httpconn=(HttpURLConnection) url.openConnection(); httpconn.setRequestMethod("POST");//區別 httpconn.setReadTimeout(5000); //post和get的不一樣之處 OutputStream outs=httpconn.getOutputStream(); outs.write(property.getBytes("UTF-8")); //發送請求 InputStream inputStream=httpconn.getInputStream(); InputStreamReader inputReader=new InputStreamReader(inputStream); BufferedReader buff=new BufferedReader(inputReader); while((str=buff.readLine())!=null){ sb.append(str); } if("插入成功!".equals(sb)) System.out.println("插入成功!"); textView.setText(sb); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ return new String(sb); } } } }
服務端主要部分代碼展現:tomcat
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO 自動生成的方法存根 //super.doPost(req, resp); String id=req.getParameter("id"); //由於服務器端的首選編碼是iso-8859-1,不是utf-8 //先按照系統默認編碼把它轉成字節數組,而後再把數組轉成字符串 id=new String(id.getBytes(),"utf-8"); String name=req.getParameter("name"); name=new String(name.getBytes(),"utf-8"); String sex=req.getParameter("sex"); sex=new String(sex.getBytes(),"utf-8"); System.out.println(name+sex); int age=Integer.parseInt(req.getParameter("age")); float weight=Float.parseFloat(req.getParameter("weight")); float hight=Float.parseFloat(req.getParameter("hight")); Connection con=null; PreparedStatement prep=null; ResultSet result=null; String sql="insert into stu_info(id,name,sex,age,weight,hight) values(?,?,?,?,?,?)"; con=DataBaseConnection.getConnection(); if(con!=null) { try { prep=con.prepareStatement(sql); prep.setString(1, id); prep.setString(2, name); prep.setString(3, sex); prep.setInt(4, age); prep.setFloat(5, weight); prep.setFloat(6, hight); int n=prep.executeUpdate(); if(n!=0)System.out.println("插入成功!"); resp.setCharacterEncoding("utf-8"); //設置這個頁面的編碼格式,若是不設置在這個頁面會顯示亂碼 //resp.setContentType("text/html;charset="); PrintWriter p=resp.getWriter(); p.println("插入成功!"); } catch (SQLException e) { // TODO 自動生成的 catch 塊 e.printStackTrace(); }finally { DataBaseConnection.closeDatabaseConnection(con, prep, result); } } }