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); } } }