Android Http get和post请求,URLConnection以及Cookie的处理

Post请求

public static String httpPost(String url) {
		String username = "", password = "";
		String str;
		HttpPost request = new HttpPost(url);
		HttpClient httpClient = new DefaultHttpClient();
		httpClient.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, 5000); // 超时设置
		httpClient.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 5000);// 连接超时
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("username", username));
		params.add(new BasicNameValuePair("password", password));
		HttpResponse response;

		try {
			HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
			request.setEntity(entity);
			response = httpClient.execute(request);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				str = EntityUtils.toString(response.getEntity());
				JSONObject json = new JSONObject(str);
				int code = json.getInt("code");
				String nickname = "";
				int usertype = -1;
				if (code == 1) {
					nickname = json.getString("nickname");
					usertype = json.getInt("usertype");
				}
				if ((nickname.equals(username)) && (code == 1)) {
					System.out.println("登陆成功!");
					CookieStore mCookieStore = ((AbstractHttpClient) httpClient).getCookieStore();
					List<Cookie> cookies = mCookieStore.getCookies();
					for (int i = 0; i < cookies.size(); i++) {
						System.out.println("session==" + cookies.get(i).getName());
					}
					for (int i = 0; i < cookies.size(); i++) {
						// 这里是读取Cookie['JSESSIONID']的值存在静态变量中,保证每次都是同一个值
						if ("JSESSIONID".equals(cookies.get(i).getName())) {
							JSESSIONID = cookies.get(i).getValue();
							System.out.println("JSESSIONID=" + JSESSIONID);
						} else {
							System.out.println("not JSESSIONID");
						}
					}


				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return str;
	}

Get请求,这里发送的Cookies会变

public static String httpGet(String url) {
		HttpClient httpClient = new DefaultHttpClient();
		httpClient.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, 10000);
		httpClient.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 10000);
		try {
			String urlEncode = encode(url, "UTF-8");
			HttpGet request = new HttpGet(urlEncode);
			HttpResponse response;
			if (mCookies != null) {
				for (int i = 0; i < mCookies.size(); i++) {
					request.addHeader("Cookie", mCookies.get(i).getName() + "=" + mCookies.get(i).getValue());
				}
			}
			response = httpClient.execute(request);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				HTTP_RESULT = true;
				HttpEntity entity = response.getEntity();
				result = EntityUtils.toString(entity, HTTP.UTF_8);
				CookieStore mCookieStore = ((AbstractHttpClient) httpClient).getCookieStore();
				List<Cookie> cookies = mCookieStore.getCookies();
				List<Integer> mCookieIndex = new ArrayList<Integer>();
				if (mCookies != null) {
					for (int i = 0; i < mCookies.size(); i++) {
						for (int j = 0; j < cookies.size(); j++) {
							boolean cookieEq = mCookies.get(i).getName().equals(cookies.get(j).getName());
							if (cookieEq) {
								mCookieIndex.add(i);
							}
						}
					}
					for (int i = 0; i < mCookieIndex.size(); i++) {
						int index = mCookieIndex.get(i);
						mCookies.remove(index);
					}
				}
				mCookies.addAll(cookies);
			} else {
				HTTP_RESULT = false;
			}
		} catch (Exception e) {
			HTTP_RESULT = false;
			mCookies.clear();
			System.out.println("网络连接失败 HttpUtils!");
			e.printStackTrace();
		}
		return result;
	}

URLConnection

public static String getRequestSync(String url1) {
		try {
			// 模拟器测试时,请使用外网地址
			URL url = new URL(url1);
			URLConnection con = url.openConnection();
			int responseCode = ((HttpURLConnection) con).getResponseCode();
			String result = "http status code: " + responseCode + "\n";
			// HttpURLConnection.HTTP_OK
			if (HttpURLConnection.HTTP_OK != responseCode) {
				Log.i("HTTPUtils", "connection failed");
				return null;
			}
			InputStream is = con.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(is);
			ByteArrayBuffer bab = new ByteArrayBuffer(32);
			int current = 0;
			while ((current = bis.read()) != -1) {
				bab.append((byte) current);
			}
			result = EncodingUtils.getString(bab.toByteArray(), HTTP.UTF_8);
			bis.close();
			is.close();
			return result;
		} catch (Exception e) {
			Log.e("HTTPUtils", "connection exception");
			return null;
		}
	}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值