/**
         * 用 HttpClient 的 Get 请求访问服务器
         *
         * @param url_path
         * @param userName
         * @param userPass
         * @return
         */
        private String HttpClientGetMeth(String url_path, String userName,
                String userPass) {
            String result = "";

try {
                url_path = url_path + "?username="
                        + URLEncoder.encode(userName, "utf-8") + "&userpass="
                        + URLEncoder.encode(userPass, "utf-8");

HttpGet get = new HttpGet(url_path);
                HttpParams params = new BasicHttpParams();
                HttpConnectionParams.setConnectionTimeout(params, 5 * 1000);
                HttpConnectionParams.setSoTimeout(params, 5 * 1000);

HttpClient httpClient = new DefaultHttpClient(params);
                HttpResponse response = httpClient.execute(get);

if (response.getStatusLine().getStatusCode() == 200) {
                    HttpEntity resEntity = response.getEntity();
                    result = EntityUtils.toString(resEntity, "utf-8");
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        }

/**
         * 用 HttpClient 的 Post 请求访问服务器
         *
         * @param url_path
         * @param userName
         * @param userPass
         * @return
         */
        private String HttpClientPostMeth(String url_path, String userName,
                String userPass) {
            String result = "";

HttpPost post = new HttpPost(url_path);
            HttpParams params = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(params, 5 * 1000);
            HttpConnectionParams.setSoTimeout(params, 5 * 1000);

List<NameValuePair> pair = new ArrayList<NameValuePair>();
            pair.add(new BasicNameValuePair("username", userName));
            pair.add(new BasicNameValuePair("userpass", userPass));

try {
                HttpEntity entity = new UrlEncodedFormEntity(pair, "utf-8");
                post.setEntity(entity);

HttpClient httpClient = new DefaultHttpClient(params);
                HttpResponse response = httpClient.execute(post);

if (response.getStatusLine().getStatusCode() == 200) {
                    HttpEntity resEntity = response.getEntity();
                    result = EntityUtils.toString(resEntity, "utf-8");
                }

} catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

return result;
        }

/**
         * 用 HttpURLConnection 的 Post 请求访问服务器
         *
         * @param url_path
         * @param userName
         * @param userPass
         * @return
         */
        private String URLConnectionPosttMeth(String url_path, String userName,
                String userPass) {
            String result = "";
            // ?username=admin&userpass=123456
            try {
                URL url = new URL(url_path);
                HttpURLConnection conn = (HttpURLConnection) url
                        .openConnection();
                conn.setConnectTimeout(5 * 1000);
                conn.setReadTimeout(5 * 1000);

conn.setRequestMethod("POST");// 设置请求方式为 Post 方式
                conn.setDoInput(true);// 设置是否可以读取
                conn.setDoOutput(true);// 设置是否可以写入

DataOutputStream dos = new DataOutputStream(
                        conn.getOutputStream());
                // 把中文进行utf-8编码,服务器通过request.setCharacterEncoding("utf-8");解码
                String params = "username="
                        + URLEncoder.encode(userName, "utf-8") + "&userpass="
                        + URLEncoder.encode(userPass, "utf-8");

dos.write(params.getBytes());
                dos.flush();
                dos.close();

if (conn.getResponseCode() == 200) {
                    InputStream is = conn.getInputStream();// 获得输入流对象读取服务器响应结果

// 服务器需要通过response.setCharacterEncoding("utf-8");//设置服务器响应编码为中文编码,为了解决android端接收的数据能不乱码
                    // 因为有中文乱码,需要转码,通过把字节流转换为缓存字符流,同时设置编码,实现转码
                    InputStreamReader reader = new InputStreamReader(is,
                            "utf-8");

char[] buf = new char[1024];
                    reader.read(buf);
                    // Log.i("Bright", buf.length + "------post------");
                    result = new String(buf, 0, buf.length);
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        }

/**
         * 用 HttpURLConnection 的 Get 请求访问服务器
         *
         * @param url_path
         * @param userName
         * @param userPass
         * @return
         */
        private String URLConnectionGetMeth(String url_path, String userName,
                String userPass) {
            String result = "";
            // ?username=admin&userpass=123456
            try {
                // 把中文进行utf-8编码,服务器通过request.setCharacterEncoding("utf-8");解码
                url_path = url_path + "?username="
                        + URLEncoder.encode(userName, "utf-8") + "&userpass="
                        + URLEncoder.encode(userPass, "utf-8");

URL url = new URL(url_path);
                HttpURLConnection conn = (HttpURLConnection) url
                        .openConnection();
                conn.setConnectTimeout(5 * 1000);
                conn.setReadTimeout(5 * 1000);
                if (conn.getResponseCode() == 200) {
                    InputStream is = conn.getInputStream();

// 服务器需要通过response.setCharacterEncoding("utf-8");//设置服务器编码为中文编码,为了解决android端接收的数据能不乱码
                    // 因为有中文乱码,需要转码,通过把字节流转换为缓存字符流,同时设置编码,实现转码
                    InputStreamReader reader = new InputStreamReader(is,
                            "utf-8");

char[] buf = new char[1024];
                    reader.read(buf);
                    // Log.i("Bright", buf.length + "------get------");
                    result = new String(buf, 0, buf.length);
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result.trim();
        }

http 网络请求的更多相关文章

  1. Angular2入门系列教程7-HTTP(一)-使用Angular2自带的http进行网络请求

    上一篇:Angular2入门系列教程6-路由(二)-使用多层级路由并在在路由中传递复杂参数 感觉这篇不是很好写,因为涉及到网络请求,如果采用真实的网络请求,这个例子大家拿到手估计还要自己写一个web ...

  2. Android之三种网络请求解析数据(最佳案例)

    AsyncTask解析数据 AsyncTask主要用来更新UI线程,比较耗时的操作可以在AsyncTask中使用. AsyncTask是个抽象类,使用时需要继承这个类,然后调用execute()方法. ...

  3. IOS开发之—— 在AFN基础上进行的网络请求的封装

    网络请求的思路:如果请求成功的话AFN的responseObject就是解析好的. 1发送网络请求:get/post/或者别的 带上URL,需要传的参数 2判断后台网络状态码有没有请求成功: 3 请求 ...

  4. Android,适合Restful网络请求封装

    借助volley.Gson类库. 优点 网络请求集中处理,返回值直接为预期的对象,不需要手动反序列,提高效率,使用时建立好model类即可. 使用效果 DataProess.Request(true, ...

  5. Android okHttp网络请求之Json解析

    前言: 前面两篇文章介绍了基于okHttp的post.get请求,以及文件的上传下载,今天主要介绍一下如何和Json解析一起使用?如何才能提高开发效率? okHttp相关文章地址: Android o ...

  6. 阶段一:通过网络请求,获得并解析JSON数据(天气应用)

    “阶段一”是指我第一次系统地学习Android开发.这主要是对我的学习过程作个记录. 在上一篇阶段一:解析JSON中提到,最近在写一个很简单的天气预报应用.即使功能很简单,但我还是想把它做成一个相对完 ...

  7. NSURLSession网络请求

    个人感觉在网上很难找到很简单的网络请求.或许是我才疏学浅 ,  所有就有了下面这一段 , 虽然都是代码 , 但是全有注释 . //1/获取文件访问路径 NSString *path=@"ht ...

  8. 【Swift】Alamofile网络请求数据更新TableView的坑

    写这篇BLOG前,有些话不得不提一下,就仅当发发恼骚吧... 今天下午为了一个Alamofire取得数据而更新TableView的问题,查了一下午的百度(360也是见鬼的一样),竟然没有一个简单明了的 ...

  9. 【WP8.1】HttpClient网络请求、进度以及终止

    工作这么长时间,起初还是喜欢用面向程序过程的思路去写代码. 慢慢的才会用面向对象的思路分析.解决问题.也算是一点点进步吧. 最近在做一个下载音乐的功能.用到了HttpClient类. 于是就简单的写了 ...

  10. ios htttp网络请求cookie的读取与写入(NSHTTPCookieStorage)

    当你访问一个网站时,NSURLRequest都会帮你主动记录下来你访问的站点设置的Cookie,如果 Cookie 存在的话,会把这些信息放在 NSHTTPCookieStorage 容器中共享,当你 ...

随机推荐

  1. 夺命雷公狗-----React---6--props多属性的传递

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  2. 15. 星际争霸之php设计模式--策略模式

    题记==============================================================================本php设计模式专辑来源于博客(jymo ...

  3. Hadoop实战5:MapReduce编程-WordCount统计单词个数-eclipse-java-windows环境

    Hadoop研发在java环境的拓展 一 背景 由于一直使用hadoop streaming形式编写mapreduce程序,所以目前的hadoop程序局限于python语言.下面为了拓展java语言研 ...

  4. A New Effect About My Plugin render

  5. [Machine-Learning] 熟悉 Numpy

    Numpy 是 Python 中的一个模块,主要用于处理数学和计算相关的问题,这里是一个入门的介绍. 导入 习惯上可以这样导入: import numpy as np 在 machine learni ...

  6. 2016年江西理工大学C语言程序设计竞赛(初级组)

    问题 A: 木棒根数 解法:把所有的情况保存下来,加一下就好 #include<bits/stdc++.h> using namespace std; map<char,int> ...

  7. Android中SQLite应用详解

    上次我向大家介绍了SQLite的基本信息和使用过程,相信朋友们对SQLite已经有所了解了,那今天呢,我就和大家分享一下在Android中如何使用SQLite. 现在的主流移动设备像Android.i ...

  8. [问题2014S02] 复旦高等代数II(13级)每周一题(第二教学周)

    问题2014S02  设实系数多项式 \begin{eqnarray*}f(x) &=& a_nx^n+a_{n-1}x^{n-1}+\cdots+a_1x+a_0, \\ g(x) ...

  9. 不用安装Oracle_Client就能使用PLSQL_Developer

    1. 下载oracle的客户端程序包(30M)       只需要在Oracle官方网站下载一个叫Instant Client Package的软件就可以了,这个软件不需要安装,只要解压就可以用了,很 ...

  10. 安装DotNetCore.1.0.0-VS2015Tools.Preview2失败解决方案

    1.把安装文件放入非系统盘 2.命令行带参数运行: DotNetCore.1.0.0-VS2015Tools.Preview2.0.1.exe SKIP_VSU_CHECK=1 或 DotNetCor ...