所進行HTTP編程前首先要明確究竟使用哪種式進行數據請求
androidHttp編程兩種:1、HttpURLConnection;2、HttpClient
首先介紹HttpURLConnection式get請求post請求:
[java] view
plaincopyprint?
private Map paramsValue;
String urlPath=null;
// 發送
public void initData(){
urlPath="";
paramsValue=new HashMap();
paramsValue.put("username", "111");
paramsValue.put("password", "222");
}
private Map paramsValue;
String urlPath=null;
// 發送
public void initData(){
urlPath="";
paramsValue=new HashMap();
paramsValue.put("username", "111");
paramsValue.put("password", "222");
}
get式發起請求:
[java] view
plaincopyprint?
private boolean sendGETRequest(String path, Map params) throws Exception {
boolean success=false;
// StringBuilder用組拼請求址參數
StringBuilder sb = new StringBuilder();
sb.append(path).append("?");
if (params != null && params.size() != 0) {
for (Map.Entry entry : params.entrySet()) {
// 請求參數文需要進行URLEncoder編碼 gbk/utf8
sb.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "utf-8"));
sb.append("&");
}
sb.deleteCharAt(sb.length() - 1);
}
URL url = new URL(sb.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(20000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() == 200) {
success= true;
}
if(conn!=null)
conn.disconnect();
return success;
}
private boolean sendGETRequest(String path, Map params) throws Exception {
boolean success=false;
// StringBuilder用組拼請求址參數
StringBuilder sb = new StringBuilder();
sb.append(path).append("?");
if (params != null && params.size() != 0) {
for (Map.Entry entry : params.entrySet()) {
// 請求參數文需要進行URLEncoder編碼 gbk/utf8
sb.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "utf-8"));
sb.append("&");
}
sb.deleteCharAt(sb.length() - 1);
}
URL url = new URL(sb.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(20000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() == 200) {
success= true;
}
if(conn!=null)
conn.disconnect();
return success;
}
postt式發起請求:
[java] view
plaincopyprint?
private boolean sendPOSTRequest(String path,Map params) throws Exception{
boolean success=false;
//StringBuilder用組拼請求參數
StringBuilder sb = new StringBuilder();
if(params!=null &?ms.size()!=0){
for (Map.Entry entry : params.entrySet()) {
sb.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "utf-8"));
sb.append("&");
}
sb.deleteCharAt(sb.length()-1);
}
//entity請求體部內容
//文則UTF-8編碼username=%E4%B8%AD%E5%9B%BD&password=123
byte[] entity = sb.toString().getBytes();
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(2000);
// 設置POST式
conn.setRequestMethod("POST");
// Post 請求能使用緩存
// urlConn.setUseCaches(false);
//要向外輸數據要設置
conn.setDoOutput(true);
// 配置本連接Content-type配置application/x-www-form-urlencoded
//設置content-type獲輸流便於想服務器發送信息
//POST請求定要設置
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", entity.length+"");
// 要註意connection.getOutputStream隱含進行connect
OutputStream out = conn.getOutputStream();
//寫入參數值
out.write(entity);
//刷新、關閉
out.flush();
out.close();
if (conn.getResponseCode() == 200) {
success= true;
}
if(conn!=null)
conn.disconnect();
return success;
}
private boolean sendPOSTRequest(String path,Map params) throws Exception{
boolean success=false;
//StringBuilder用組拼請求參數
StringBuilder sb = new StringBuilder();
if(params!=null &?ms.size()!=0){
for (Map.Entry entry : params.entrySet()) {
sb.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "utf-8"));
sb.append("&");
}
sb.deleteCharAt(sb.length()-1);
}
//entity請求體部內容
//文則UTF-8編碼username=%E4%B8%AD%E5%9B%BD&password=123
byte[] entity = sb.toString().getBytes();
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(2000);
// 設置POST式
conn.setRequestMethod("POST");
// Post 請求能使用緩存
// urlConn.setUseCaches(false);
//要向外輸數據要設置
conn.setDoOutput(true);
// 配置本連接Content-type配置application/x-www-form-urlencoded
//設置content-type獲輸流便於想服務器發送信息
//POST請求定要設置
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", entity.length+"");
// 要註意connection.getOutputStream隱含進行connect
OutputStream out = conn.getOutputStream();
//寫入參數值
out.write(entity);
//刷新、關閉
out.flush();
out.close();
if (conn.getResponseCode() == 200) {
success= true;
}
if(conn!=null)
conn.disconnect();
return success;
}
介紹HttpClient式相比HttpURLConnectionHttpClient封裝更簡單易用些看實例:
get式發起請求:
[java] view
plaincopyprint?
public String getRequest(String UrlPath,Map params){
String content=null;
StringBuilder buf = new StringBuilder();
if(params!=null &?ms.size()!=0){
for (Map.Entry entry : params.entrySet()) {
buf.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "utf-8"));
buf.append("&");
}
buf.deleteCharAt(buf.length()-1);
}
content= buf.toString();
HttpClient httpClient = new DefaultHttpClient();
HttpGet getMethod = new HttpGet(content);
HttpResponse response = null;
try {
response = httpClient.execute(getMethod);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
if (response!=null&&response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
try {
content = EntityUtils.toString(response.getEntity());
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return content;
}
public String getRequest(String UrlPath,Map params){
String content=null;
StringBuilder buf = new StringBuilder();
if(params!=null &?ms.size()!=0){
for (Map.Entry entry : params.entrySet()) {
buf.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "utf-8"));
buf.append("&");
}
buf.deleteCharAt(buf.length()-1);
}
content= buf.toString();
HttpClient httpClient = new DefaultHttpClient();
HttpGet getMethod = new HttpGet(content);
HttpResponse response = null;
try {
response = httpClient.execute(getMethod);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
if (response!=null&&response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
try {
content = EntityUtils.toString(response.getEntity());
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return content;
}
postt式發起請求:
[java] view
plaincopyprint?
private boolean sendPOSTRequestHttpClient(String path,Map params) throws Exception {
boolean success = false;
// 封裝請求參數
List pair = new ArrayList();
if (params != null && !params.isEmpty()) {
for (Map.Entry entry : params.entrySet()) {
pair.add(new BasicNameValuePair(entry.getKey(), entry
.getValue()));
}
}
// 請求參數變請求體部
UrlEncodedFormEntity uee = new UrlEncodedFormEntity(pair, "utf-8");
// 使用HttpPost象設置發送URL路徑
HttpPost post = new HttpPost(path);
// 發送請求體
post.setEntity(uee);
// 創建瀏覽器象POST象向服務器發送並返響應消息
DefaultHttpClient dhc = new DefaultHttpClient();
HttpResponse response = dhc.execute(post);
if (response.getStatusLine().getStatusCode() == 200) {
success = true;
}
return success;
}
private boolean sendPOSTRequestHttpClient(String path,Map params) throws Exception {
boolean success = false;
// 封裝請求參數
List pair = new ArrayList();
if (params != null && !params.isEmpty()) {
for (Map.Entry entry : params.entrySet()) {
pair.add(new BasicNameValuePair(entry.getKey(), entry
.getValue()));
}
}
// 請求參數變請求體部
UrlEncodedFormEntity uee = new UrlEncodedFormEntity(pair, "utf-8");
// 使用HttpPost象設置發送URL路徑
HttpPost post = new HttpPost(path);
// 發送請求體
post.setEntity(uee);
// 創建瀏覽器象POST象向服務器發送並返響應消息
DefaultHttpClient dhc = new DefaultHttpClient();
HttpResponse response = dhc.execute(post);
if (response.getStatusLine().getStatusCode() == 200) {
success = true;
}
return success;
}