get/post+server of HttpURLConnection

httpURLConnection uses the get method to send a small amount of request parameter data to the background, and the background goes to the database to get the data.

  • At the beginning, the background data was not obtained and always reported such an error:
  •  Note: further occurrences of HTTP request parsing errors will be logged at DEBUG level.
    java.lang.IllegalArgumentException: Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC 3986
  • Later, I found information on the Internet and said that after the Tomcat9.0 version, there were new regulations, and the writing of URLs was stricter. Only English letters and numbers and some special characters were accepted. The parameters requested here are Chinese, so it will not work. After encoding Chinese later becomes something like:
  • It can be received by sending it in the form of %DEC887%SDW3324%. So I wrote the following code

Connection address and parameters:

           String name="Tang Jingshu";
            String sex="Female";
            try {
        //The tomcat9 version does not accept Chinese characters in the link address, it needs to be encoded to receive
                name=URLEncoder.encode(name, "utf-8");
                sex =URLEncoder.encode(sex, "utf-8");
            } catch (UnsupportedEncodingException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            //? sign separates addresses and parameters, between parameters and parameters Concatenate
            String Url=arg0[0]+"?name="+name+"&sex="+sex; with &

HTTP get method

The main part of the code on the Android side:

/**
 * 
 * @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;
			}
		}
    }
}

Server-side code:

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

http post method:

The main part of the code on the Android side shows:

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

The main part of the code display of the server:

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

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325828394&siteId=291194637