Android網路請求操作httpurlconnection和httpclient基本使用
1. 網路請求操作中Get請求和Post請求有什麼區別?
1) Get是向伺服器發索取資料的一種請求,而Post是向伺服器提交資料的一種請求
2) Get是獲取資訊,而不是修改資訊,類似資料庫查詢功能一樣,資料不會被修改
3) 對於get方式,伺服器端用Request.QueryString獲取變數的值,對於post方式,伺服器端用Request.Form獲取提交的資料
4) get傳送的資料量較小,不能大於2KB。post傳送的資料量較大,一般被預設為不受限制。但理論上,IIS4中最大量為80KB,IIS5中為100KB
5) Get
2. http請求返回狀態碼
狀態碼 |
含義 |
100~199 |
表示成功接收請求,要求客戶端繼續提交下一次請求才能完成整個處理過程 |
200~299 |
表示成功接收請求並已完成整個處理過程 |
300~399 |
為完成請求,客戶需進一步細化請求。例如,請求的資源已經移動一個新地址 |
400~499 |
客戶端的請求有錯誤 |
500~599 |
伺服器端出現錯誤 |
常用狀態碼:
200(正常):表示一切正常,返回的是正常請求結果
302/307(臨時重定向):指出被請求的文件已被臨時移動到別處,此文件的新的URL 在Location響應頭中給出。
304(未修改):表示客戶機快取的版本是最新的,客戶機可以繼續使用它,無需到服務器請求。
404(找不到):伺服器上不存在客戶機所請求的資源。
500(伺服器內部錯誤):伺服器端的程式發生錯
3. httpurlconnection基本用法
1) 基本的Get請求
try { String url = "http://apis.juhe.cn/mobile/get" + "?phone=" + URLEncoder.encode("13429667914", "utf-8") + "&key=" + "3a0152ec37d15dee57b380669fe714a2"; URL url1 = new URL(url); HttpURLConnection urlConn = (HttpURLConnection) url1.openConnection(); urlConn.setRequestProperty("content-type", "application/json"); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setConnectTimeout(5 * 1000); // 設定請求方式為 PUT urlConn.setRequestMethod("GET"); urlConn.setRequestProperty("Charset", "UTF-8"); Log.i("888", "" + urlConn.getResponseCode()); if (urlConn.getResponseCode() == 200) { BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); String str; StringBuffer sb = new StringBuffer(); while ((str = reader.readLine()) != null) { sb.append(str); } Log.i("esasdasd", "result:" + sb.toString()); Message message = new Message(); message.what = 111; message.obj = sb.toString(); handler.sendMessage(message); urlConn.disconnect(); } } catch (Exception e) { e.printStackTrace(); }
2) 基本的Post請求
URL url1 = null;
try {
url1 = new URL(http://192.168.2.69:8888/user/sign-in?ds=mobile);
} catch (MalformedURLException e) {
e.printStackTrace();
}
if (url1 != null) {
try {
HttpURLConnection urlConn = (HttpURLConnection) url1.openConnection();
urlConn.setRequestProperty("content-type", "application/json");
urlConn.setDoInput(true);
urlConn.setDoOutput(true);
urlConn.setConnectTimeout(5 * 1000);
//設定請求方式為 PUT
urlConn.setRequestMethod("POST");
urlConn.setRequestProperty("Content-Type", "application/json");
urlConn.setRequestProperty("Accept", "application/json");
urlConn.setRequestProperty("Charset", "UTF-8");
DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream());
//寫入請求引數
JSONObject jsonObject = new JSONObject();
jsonObject.put("username", "username");
jsonObject.put("email", "email");
jsonObject.put("password", "password");
dos.writeBytes(jsonObject.toString());
dos.flush();
dos.close();
Log.i("888", ""+urlConn.getResponseCode());
if (urlConn.getResponseCode() == 200) {
// 請求返回的資料
InputStream in = urlConn.getInputStream();
String a = null;
try {
byte[] data1 = new byte[in.available()];
in.read(data1);
// 轉成字串
a = new String(data1);
System.out.println(a);
final StringBuffer sb = new StringBuffer(a);
handler.post(new Runnable() {
@Override
public void run() {
List<Register_name> list=parseJson(sb.toString());
Message message=new Message();
message.obj=list;
handler.sendMessage(message);
}
});
} catch (Exception e1) {
e1.printStackTrace();
}
urlConn.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
}
}
4. HttpclientGet請求基本使用
1) client = new DefaultHttpClient();
// 保持和伺服器登入狀態一直是登入著的,必不可少設定全域性唯一的Cookie
((AbstractHttpClient) client).setCookieStore(FirstActivity.cookieStore);
HttpGet post = new HttpGet(url);
post.addHeader("contentType", "application/json");
try {
postResp = client.execute(post);
int return_code = postResp.getStatusLine().getStatusCode();
if (return_code == 200) {
final String recives = EntityUtils.toString(postResp.getEntity());
Log.d("recives", recives);
handler.post(new Runnable() {
@Override
public void run() {
Message message = new Message();
message.what = 222;
message.obj = recives.toString();
handler.sendMessage(message);
}
});
} else if (return_code == 400) {
Log.d("recives", "error" + return_code);
} else {
Log.d("recives", "error" + return_code);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
2) Post基本使用
client = new DefaultHttpClient();
// 保持和伺服器登入狀態一直是登入著的,必不可少設定全域性唯一的Cookie
((AbstractHttpClient) client).setCookieStore(FirstActivity.cookieStore);
HttpPost post = new HttpPost(url);
post.addHeader("contentType", "application/json");
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("username", "username");
jsonObject.put("email", "username");
jsonObject.put("password", "password");
post.setEntity(new StringEntity(jsonObject.toString(), "utf-8"));
postResp = client.execute(post);
int return_code = postResp.getStatusLine().getStatusCode();
if (return_code == 200) {
final String recives = EntityUtils.toString(postResp.getEntity());
Log.d("recives", recives);
handler.post(new Runnable() {
@Override
public void run() {
Message message = new Message();
message.what=222;
message.obj = recives.toString();
handler.sendMessage(message);
}
});
} else if (return_code == 400) {
Log.d("recives", "error"+return_code);
} else {
Log.d("recives", "error"+return_code);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
5. 程式碼缺少的部分
URL url1 = null;
private HttpClient client;
HttpResponse postResp;
private final static BasicCookieStore cookieStore = new BasicCookieStore();
Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 111:
String string=(String) msg.obj;
Toast.makeText(FirstActivity.this, string, Toast.LENGTH_SHORT).show();
break;
case 222:
String string1=(String) msg.obj;
Toast.makeText(FirstActivity.this, string1, Toast.LENGTH_SHORT).show();
break;
default:
break;
}
super.handleMessage(msg);
}
};
6. 補充的部分
1.// 保持和伺服器登入狀態一直是登入著的,必不可少設定全域性唯一的Cookie
((AbstractHttpClient) client).setCookieStore(LoginHttpThread.cookieStore);