【Android基礎知識】HttpUrlConnection使用doGet和doPost方式和服務器交互

這裏介紹HttpUrlConnection使用get方式或post方式和服務器進行數據交互

1.建立服務器端Web程序MyServlet

在doGet方法中調用doPost方法,在doPost方法中接收客戶端發送來的數據

public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String name = request.getParameter("name");
		String age = request.getParameter("age");
		//response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		out.print("name ="+name+" age= "+age);
		//new String(name.getBytes("iso-8859-1"),"utf-8"); 轉碼
		System.out.println("name ="+name+" age= "+age);
}
創建一個Jsp表單
<body>
    <form action="MyServlet" method="get">
    	name:<input type="text" name = "name"/><br/>
    	age:   <input type="text" name = "age"/><br/>
    	<input type="submit" value="submit"/>
    </form>
  </body>
頁面如下
發送一個請求後,服務器端返回請求的數據

2.使用Android客戶端和服務器進行交互

網絡請求線程類,分別使用doGet和doPost方法請求服務器
public class HttpThread extends Thread{
	String url;
	String age;
	String name;
	
	public HttpThread(String url,String age,String name){
		this.url = url;
		this.age = age;
		this.name = name;
	}
	private void doGet(){
		//get方式請求數據是在url中拼接的
		url = url+"?name="+name+"&age="+age;
//		URLEncoder.encode(name,"utf-8");//轉碼,防止中文亂碼
		try {
			URL httpUrl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
			conn.setReadTimeout(3000);
			conn.setRequestMethod("GET");
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String str;
			StringBuffer sb = new StringBuffer();
			while((str = bufferedReader.readLine())!= null){
				sb.append(str);
			}
			Log.i("meng.li","result: "+sb.toString());
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	private void doPost(){
		Properties properties = System.getProperties();
		properties.list(System.out);
		try {
			URL httpUrl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
			conn.setReadTimeout(3000);
			conn.setRequestMethod("POST");
			
			OutputStream out = conn.getOutputStream();
			String content = "name="+name+"&age="+age;
			out.write(content.getBytes());
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String str;
			StringBuffer sb = new StringBuffer();
			while((str = bufferedReader.readLine())!= null){
				sb.append(str);
			}
			Log.i("meng.li","result: "+sb.toString());
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	@Override
	public void run() {
		doGet();
//		doPost();
	}
}
調用類
public class RegisteActivity extends Activity {
	private Button regist;
	private EditText name;
	private EditText age;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        name = (EditText)findViewById(R.id.name);
        age = (EditText)findViewById(R.id.age);
        regist = (Button)findViewById(R.id.submit);
        regist.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String url = "http://192.168.199.126:8080/Server/MyServlet";
				new HttpThread(url, age.getText().toString(), name.getText().toString()).start();
			}
		});
    }
}





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章