Post与Get区别:
(1)GET提交,请求的数据会附在URL之后(就是把数据放置在HTTP协议头中),以?分割URL和传输数据,多个参数用&连接;例如:login.action?name=hyddd&password=idontknow&verify=%E4%BD%A0 %E5%A5%BD。如果数据是英文字母/数字,原样发送,如果是空格,转换为+,如果是中文/其他字符,则直接把字符串用BASE64加密,得出如: %E4%BD%A0%E5%A5%BD,其中%XX中的XX为该符号以16进制表示的ASCII。 POST提交:把提交的数据放置在是HTTP包的包体中。上文示例中红色字体标明的就是实际的传输数据 因此,GET提交的数据会在地址栏中显示出来,而POST提交,地址栏不会改变 (2)传输数据的大小:首先声明:HTTP协议没有对传输的数据大小进行限制,HTTP协议规范也没有对URL长度进行限制。 而在实际开发中存在的限制主要有: GET:特定浏览器和服务器对URL长度有限制,例如IE对URL长度的限制是2083字节(2K+35)。对于其他浏览器,如Netscape、FireFox等,理论上没有长度限制,其限制取决于操作系统的支持。 因此对于GET提交时,传输数据就会受到URL长度的限制。 POST:由于不是通过URL传值,理论上数据不受限。但实际各个WEB服务器会规定对post提交数据大小进行限制,Apache、IIS6都有各自的配置。 (3)安全性: .POST的安全性要比GET的安全性高。注意:这里所说的安全性和上面GET提到的“安全”不是同个概念。上面“安全”的含义仅仅是不作数据修改,而这里安全的含义是真正的Security的含义,比如:通过GET提交数据,用户名和密码将明文出现在URL上,因为(1)登录页面有可能被浏览器缓存, (2)其他人查看浏览器的历史纪录,那么别人就可以拿到你的账号和密码了,除此之外,使用GET提交数据还可能会造成Cross-site request forgery攻击
android 中常用的网络连接方式有两种 HttpUrlConnection 与HttpClient
public class MyHttpClient { private final int CONNECT_TIME_OUT = 30 * 1000; private int READ_TIME_OUT = 90 * 1000; private DefaultHttpClient mHttpClient; private HttpClient getHttpClient() { if(mHttpClient == null) { mHttpClient = new DefaultHttpClient(); } return mHttpClient; } /** * http访问数据,默认返回的数据为UTF-8编码 * * @param url * @return * @throws IOException */ public String getData(String url) throws IOException { HttpClient httpClient = getHttpClient(); HttpGet request = new HttpGet(url); HttpResponse response = httpClient.execute(request); String result =null; if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { result =EntityUtils.toString(response.getEntity()); } return result== null? "" : result; } /** * post提交数据 * * @param url * 提交地址 * @param params * 参数 * @return * @throws ClientProtocolException * @throws IOException */ public String postData(String url, Map<String, String> params) throws ClientProtocolException, IOException { return postData(url, params, "UTF-8"); } /** * post提交数据 * * @param url * 提交地址 * @param params * 参数 * @param encoding * 参数编码 * @return * @throws ClientProtocolException * @throws IOException */ public String postData(String url, Map<String, String> params, String encoding) throws ClientProtocolException, IOException { HttpClient httpClient = getHttpClient(); List<NameValuePair> param = new ArrayList<NameValuePair>(); // param.add(new BasicNameValuePair("par", "request-post")); Iterator<Entry<String, String>> iterator = params.entrySet().iterator(); while (iterator.hasNext()) { Entry<String, String> entry = iterator.next(); param.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } HttpPost request = new HttpPost(url); HttpEntity entity = new UrlEncodedFormEntity(param, encoding); request.setEntity(entity); httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECT_TIME_OUT); // 设置请求超时时间 httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, READ_TIME_OUT); // 读取超时 HttpResponse response = httpClient.execute(request); String result = null; if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { result = EntityUtils.toString(response.getEntity()); } return result == null ? "" : result; } }
package com.net; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.InetSocketAddress; import java.net.URL; /** * @author Administrator * 使用HTTPURLConnection */ public class MyHttp { private final int CONNECT_TIME_OUT = 30 * 1000; private int READ_TIME_OUT = 90 * 1000; /**设置读取数据的超时时间(一般不需要设置,只有一次下载大量数据时设置) * @param sec 单位秒 */ public void setReadTimeOut(int sec) { READ_TIME_OUT = sec * 1000; } /** * @param data * 需要上传的data * @param url * HTTP地址 * @return 返回结果的输入流 */ public InputStream post(byte[] postData, String url) { InputStream stream = null; OutputStream output = null; try { HttpURLConnection conn = null; conn = createHttpURLConnection(url); conn.setConnectTimeout(CONNECT_TIME_OUT); conn.setReadTimeout(READ_TIME_OUT); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("User-Agent", "android"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.connect(); output = conn.getOutputStream(); output.write(postData); output.flush(); stream = conn.getInputStream(); } catch (IOException e) { System.out.println("post exception "+url); } finally { close(null, output); } return stream; } /** * @param data * 需要上传的data * @param urlString * HTTP地址 * @return 返回结果的字节数组 */ public byte[] postData(String data, String urlString) { byte[] postData = data == null? new byte[0] : data.getBytes(); InputStream is = post(postData, urlString); ByteArrayOutputStream baos = null; baos = new ByteArrayOutputStream(); byte[] result = null; result = StreamOperate.readStream(is, baos); close(is, baos); return result; } /** * 通过get方式获取数据 * @param sUrl * @return */ public InputStream get(String url) { InputStream is = null; try { HttpURLConnection conn = createHttpURLConnection(url); conn.setConnectTimeout(CONNECT_TIME_OUT); conn.setReadTimeout(READ_TIME_OUT); conn.setRequestMethod("GET"); is =conn.getInputStream(); } catch (Exception e) { e.printStackTrace(); System.out.println("get exception "+url); } return is; } /** * * @param sUrl * @return */ public byte[] getData(String sUrl) { InputStream is = get(sUrl); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] result = null; result = StreamOperate.readStream(is, baos); close(is , baos); return result; } /** * @param sUrl * @return 获取httpUrlConnection */ private HttpURLConnection createHttpURLConnection(String sUrl) { try { URL url = new URL(sUrl); if (!isGprsNet()) { java.net.Proxy p = new java.net.Proxy(java.net.Proxy.Type.HTTP, new InetSocketAddress(android.net.Proxy.getDefaultHost(), android.net.Proxy.getDefaultPort())); HttpURLConnection conn = (HttpURLConnection) url.openConnection(p); return conn; } else { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); return conn; } } catch (Exception e) { } return null; } /** * @return判断是否为net */ private boolean isGprsNet() { String proxyHost = android.net.Proxy.getDefaultHost(); return proxyHost == null; } private void close(InputStream is, OutputStream os) { try { if (is != null) { is.close(); is = null; } if (os != null) { os.close(); os = null; } } catch (IOException e) { e.printStackTrace(); } } }
AsyncTask 工具类的用法
public class MyHttpSyn extends AsyncTask<String, Integer, String> { private Activity mContext; public MyHttpSyn(Activity context) { mContext = context; } protected String doInBackground(String... params) { String sUrl = "http://www.baidu.com"; MyHttpClient httpClient = new MyHttpClient(); String sResult = null; try { sResult = httpClient.getUrl(sUrl); } catch (IOException e) { e.printStackTrace(); } return sResult; } protected void onPreExecute() { super.onPreExecute(); Toast.makeText(mContext, "begin load data", Toast.LENGTH_SHORT).show(); } protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); } protected void onPostExecute(String result) { super.onPostExecute(result); Toast.makeText(mContext, "end load data", Toast.LENGTH_SHORT).show(); TextView tv=(TextView)mContext.findViewById(R.id.tx); tv.setText(result); Log.d("async" , "end"); } }