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請求的參數會跟在url後進行傳遞,請求的數據會附在URL之後,以?分割URL和傳輸數據,參數之間以&相連,%XX中的XX爲該符號以16進製表示的ASCII,如果數據是英文字母/數字,原樣發送,如果是空格,轉換爲+,如果是中文/其他字符,則直接把字符串用BASE64加密, get安全性非常低,post安全性較高
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);