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

1.        网络请求操作中Get请求和Post请求有什么区别?

1)        Get是向服务器发索取数据的一种请求,而Post是向服务器提交数据的一种请求

2)        Get是获取信息,而不是修改信息,类似数据库查询功能一样,数据不会被修改

3)     对于get方式,服务器端用Request.QueryString获取变量的值,对于post方式,服务器端用Request.Form获取提交的数据

4)     get传送的数据量较小,不能大于2KBpost传送的数据量较大,一般被默认为不受限制。但理论上,IIS4中最大量为80KBIIS5中为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.后续会继续补充

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值