Android客户端提交数据到服务器有GET和POST以及AsyncHttpClient三种方法
一.GET和POST的区别 1.地址栏传参 2.POST提交数据需要带参(Content_type.Content_length)
但shi都需要它:
class MyTask extends AsyncTask { PRivate HttpURLConnection conn; @Override protected Object doInBackground(Object[] objects) { //获取参数的值 String uname = objects[0].toString(); String upwd = objects[1].toString(); String path = objects[2].toString(); String type = objects[3].toString(); String str = "uname=" + uname + "&upwd=" + upwd; try { if ("GET".equals(type)) { path=path+"?"+str; URL url = new URL(path); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(type); }else if ("POST".equals(type)){ URL url = new URL(path); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(type); //设置contentType contentLength conn.setRequestProperty("Content-Length",str.length()+""); conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); //设置允许对外输出数据 conn.setDoOutput(true); //将用户名和密码提交到服务器 conn.getOutputStream().write(str.getBytes()); } conn.setConnectTimeout(5000); if (conn.getResponseCode() == 200) { InputStream is = conn.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String result = br.readLine(); return result; } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Object o) { super.onPostExecute(o); } }二.AsyncHttpClient(是POST和GET的封装类) 1.需要实例化该类。 2.根据需要调用post和get方法 3.放置参数requestParams 以及路径 path new TextHttpResponseHandler()重写其方法
public void LoginByAsyncHttpClient(View view) { String uname = main_uname.getText().toString(); String upwd = main_upwd.getText().toString(); String path = getString(R.string.service_name) + "getLogin.xhtml"; AsyncHttpClient asyncHttpClient=new AsyncHttpClient(); RequestParams requestParams=new RequestParams(); requestParams.put("uname",uname); requestParams.put("upass",upwd); asyncHttpClient.post(path,requestParams,new TextHttpResponseHandler(){ @Override public void onSuccess(int statusCode, Header[] headers, String responseBody) { super.onSuccess(statusCode, headers, responseBody); Toast.makeText(MainActivity.this, responseBody, Toast.LENGTH_SHORT).show(); } @Override public void onFailure(int statusCode, Header[] headers, String responseBody, Throwable error) { super.onFailure(statusCode, headers, responseBody, error); } }); }新闻热点
疑难解答