HttpClient(Post和Get)

来源:互联网 发布:枭龙战斗机知乎 编辑:程序博客网 时间:2024/06/06 12:33

今天把网络请求中HttpClient方式敲了一下。
使用HttpClient得自己导包:

  compile files('libs/httpclient-4.4.1.jar')    compile files('libs/httpcore-4.4.1.jar')

还要在build.gradle(app)中加入如图下代码:

 packagingOptions {        exclude 'META-INF/DEPENDENCIES'        exclude 'META-INF/NOTICE'        exclude 'META-INF/LICENSE'        exclude 'META-INF/LICENSE.txt'        exclude 'META-INF/NOTICE.txt'        exclude 'META-INF/license.txt'        exclude 'META-INF/dependencies.txt'        exclude 'META-INF/notice.txt'        exclude 'META-INF/LGPL2.1'    }

就是在导包那个文件啦,千万不要写到另一个build.gradle文件中,不让会出现什么Duplicate Files。。。什么错误的,我找了一个多小时解决这个bug,感觉自己好low。
对了,要在Manifest中加权限,这个上俩篇讲了,就不讲了,还有这里继续使用了前面俩篇的那个天气预报接口。
Get方式:

  private class ThreeThread implements Runnable {        InputStream is;        BufferedReader br;        @Override        public void run() {            //获取路径            getPath();            //创建默认的客户端实例            client = new DefaultHttpClient();            //创建get请求实例            HttpGet httpGet = new HttpGet(todayWeather);            System.out.println("executing request:" + httpGet.getURI());            try {                //客户端执行get请求,返回响应实体                HttpResponse response = client.execute(httpGet);                //获取响应消息实体                HttpEntity entity = response.getEntity();                //将实体封装为流输入                is = entity.getContent();                //使用高效字符流读取                br = new BufferedReader(new InputStreamReader(is));                String line = null;                StringBuffer sb = new StringBuffer();                while ((line = br.readLine()) != null) {                    sb.append(line);                }                sb.append("\n" + "\nWays:HttpClient-GET");                content = sb.toString();                Message message = new Message();                message.what = 1;                handler.sendEmptyMessage(message.what);            } catch (IOException e) {                e.printStackTrace();            } finally {                try {                    if (is != null) {                        is.close();                    }                    if (br != null) {                        br.close();                    }                } catch (IOException e) {                    e.printStackTrace();                }            }        }    }

Post方式

 private class FourThread implements Runnable {        InputStream is;        BufferedReader br;        @Override        public void run() {            getPath();            //创建客户端对象            client = new DefaultHttpClient();            //封装地址            HttpPost httpPost = new HttpPost(todayWeather);            //用list封装要向服务器端发送的参数            List<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();            pairs.add(new BasicNameValuePair("name", "蛋蛋"));            try {                //使用UrlEncodeFormEntity对象来封装List对象                UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(pairs);                //设置使用的Entity(实体)                httpPost.setEntity(urlEncodedFormEntity);                //客户端开始向指定的网址发送请求                HttpResponse response = client.execute(httpPost);                //获得请求的Entity                HttpEntity entity = response.getEntity();                is = entity.getContent();                //读取数据                br = new BufferedReader(new InputStreamReader(is));                String line = null;                StringBuffer sb = new StringBuffer();                while((line=br.readLine())!=null){                    sb.append(line);                }                sb.append("\n").append("\n").append("Wans:HttpClient-POST");                content = sb.toString();                Message message = new Message();                message.what=1;                handler.sendEmptyMessage(message.what);            } catch (UnsupportedEncodingException e) {                e.printStackTrace();            } catch (ClientProtocolException e) {                e.printStackTrace();            } catch (IOException e) {                e.printStackTrace();            }finally {                try {                    if (is != null) {                        is.close();                    }                    if (br != null) {                        br.close();                    }                } catch (IOException e) {                    e.printStackTrace();                }            }        }    }

写来写去,其实很多都是重复的,这个和前两篇的代码是在一个MainActivity中,所以具体使用只要把它带入第二篇中的源码中,我不多讲了,我想总结一下这几种方式。
总结:
一.基本步骤:
①HttpUrlConnection的Get方式:
通过String path得到URL对象–>使用newURL(String path)方法。
打开服务器–>使用URL对象的openConnection()方法,记住强转为HttpURLConnection
连接服务器–>通过HttpURLConnection对象的connect()方法。
最后就是使用输入流读取数据了,在读取之前,要通过HttpURLConnection对象先得到输入流–>getInputStream,然后使用输入流读取就行了。
②HttpURLConnection的Post方式:
和①基本一样,只是要在打开服务器后先进行一些设置,

             //设置请求方法为POST                conn.setRequestMethod("POST");                //POST方法不能缓存数据,则需要手动设置使用缓存的值为false                conn.setUseCaches(false);

然后连接服务器。
由于Post方式和Get方式的区别在于,Post是向服务器提交数据的一种请求。所以在读取数据之前要先写数据,先通过HttpURLConnection对象的getOutputStream()方法的到一个输出流,接着可以使用DataoutputStream封装这个输出流,使用它的写方法写数据。
③HttpClient的Get方式:
创建默认客户端实例–>HttpClient client = new DefaultHttpClient()
创建Get请求实例–>HttpGet httpGet = new HttpGet(String path);
客户端执行get请求,返回响应实体–>通过HttpClient对象调用执行execute(HttpGet httpGet):HttpResponse response = client.execute(httpGet);
获取响应消息实体–>HttpEntity entity = response.getEntity();
将实体封装为流输入–>InputStream is = entity.getContent()。(虽然都是得到输入流,但是HttpURLConnection是通过自己的对象的getInputStream方法获得,而HttpClient是通过它的实体的getContent方法获取)。
最后读取数据操作一样。
④HttpClient的Post方法:
和第三种方式基本一样,不同之处是:
1.这次创建的是HttpPost对象;
2.要写数据:

 //用list封装要向服务器端发送的参数            List<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();            pairs.add(new BasicNameValuePair("name", "蛋蛋"));            try {                //使用UrlEncodeFormEntity对象来封装List对象                UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(pairs);                //设置使用的Entity(实体)                httpPost.setEntity(urlEncodedFormEntity);

3.客户端执行的是HttpPost,即将execute中的参数改为HttpPost对象。
总结还有很多不全面的,有时间在总结一下。

0 0