首页 > 系统 > Android > 正文

Android网络请求操作httpurlconnection和httpclient基本使用

2019-11-06 09:34:40
字体:
来源:转载
供稿:网友

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);

2.后续会继续补充
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表