1.android get方式发送数据到服务器端。
public static boolean doget(String actionurl, Map<String,Object> params,String chartset) throws Exception {
StringBuffer sb = new StringBuffer(actionurl);
if(params!=null && !params.isEmpty()){
sb.append("?");
for(Entry<String, Object> en : params.entrySet()){
sb.append(en.getKey()).append("=").append(URLEncoder.encode(en.getValue().toString(),chartset)).append("&");
}
sb.deleteCharAt(sb.length()-1);
}
actionurl = sb.toString();
URL url = new URL(actionurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(5000);
if(conn.getResponseCode()==200){
return true;
}
return false;
}
2.android 通过向服务器发送post请求。
public static boolean dopost(String actionurl, Map<String,Object> params,String chartset) throws Exception {
URL url = new URL(actionurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setReadTimeout(5000);
conn.setRequestProperty("enctype", "application/x-www-form-urlencoded");
StringBuffer sb = new StringBuffer();
//post请求发送的数据格式为 : name1=value1&name2=value2
if(params!=null && !params.isEmpty()){
for(Entry<String, Object> en : params.entrySet()){
sb.append(en.getKey()).append("=").append(URLEncoder.encode(en.getValue().toString(),chartset)).append("&");
}
sb.deleteCharAt(sb.length()-1);
}
byte [] buffer = sb.toString().getBytes();
conn.setRequestProperty("Content-Length", String.valueOf(buffer.length));
conn.setDoOutput(true); //特别注意,没有开启输出流将无法获取outputStream对象,
OutputStream out = conn.getOutputStream();
out.write(buffer);
if(conn.getResponseCode()==200){
return true;
}
return false;
}
/***
* 3 .通过HttpClient对象发送Post请求。
* @param actionurl
* @param params
* @return
* @throws Exception
*/
public static boolean sendHttpClientPostString(String actionurl, Map<String,Object> params,String charset) throws Exception {
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
if(params!=null && !params.isEmpty()){
for(Entry<String, Object> en : params.entrySet()){
NameValuePair pair = new BasicNameValuePair(en.getKey(), (String)en.getValue());
pairs.add(pair);
}
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs,charset);
HttpPost post = new HttpPost();
post.setURI(new URI(actionurl));
post.setEntity(entity);
HttpClient client = new DefaultHttpClient();
HttpResponse reponse = client.execute(post);
if(reponse.getStatusLine().getStatusCode()==200)
{
return true;
}
return false;
}