HttpClient--HttpClient的Get请求方式

来源:互联网 发布:大学生分期软件 编辑:程序博客网 时间:2024/04/30 02:31
/** * 使用get的方式登录 * @param userName * @param password * @return 登录的状态 */public static String loginOfGet(String userName, String password) {HttpClient client = null;try {// 定义一个客户端client = new DefaultHttpClient();// 定义一个get请求方法String data = "username=" + userName + "&password=" + password;HttpGet get = new HttpGet("http://10.0.2.2:8080/ServerItheima28/servlet/LoginServlet?" + data);// response 服务器相应对象, 其中包含了状态信息和服务器返回的数据HttpResponse response = client.execute(get);// 开始执行get方法, 请求网络// 获得响应码int statusCode = response.getStatusLine().getStatusCode();if(statusCode == 200) {InputStream is = response.getEntity().getContent();String text = getStringFromInputStream(is);return text;} else {Log.i(TAG, "请求失败: " + statusCode);}} catch (Exception e) {e.printStackTrace();} finally {if(client != null) {client.getConnectionManager().shutdown();// 关闭连接, 和释放资源}}return null;}

/** * 根据流返回一个字符串信息 * @param is * @return * @throws IOException  */private static String getStringFromInputStream(InputStream is) throws IOException {ByteArrayOutputStream baos = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len = -1;while((len = is.read(buffer)) != -1) {baos.write(buffer, 0, len);}is.close();String html = baos.toString();// 把流中的数据转换成字符串, 采用的编码是: utf-8//String html = new String(baos.toByteArray(), "GBK");baos.close();return html;}

0 0
原创粉丝点击