今天在学习android的http通信时,在一个网上的demo中,发现了一个个人感觉比较好用的HttpClient发送get请求与post请求的工具类,所以个人把它整理与修改了一下,希望能够帮助有需要的人:

import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import org.apache.http.NameValuePair;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;/** * HTTP通信的工具类 */public final class HttpUtil {    /** 定义HTTP通信的对象 */    private static HttpClient httpClient = new DefaultHttpClient();    /** 定义基础的请求URL */    private static final String BASE_URL = "http://wenwen.soso.com/p/20120206/20120206134715-1866254203.jpg";    /**     * 发送GET请求方法     * @param requestUrl 请求的URL     * @return 响应的数据     */    public static InputStream sendGetRequest(String requestUrl){        /** 创建get请求对象 */        HttpGet httpGet = new HttpGet(BASE_URL + requestUrl);        try {            /** 执行GET请求 */            HttpResponse response = httpClient.execute(httpGet);            /** 判断响应的状态码: 200代表响应成功 */            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){                /** 获取响应的实体 */                HttpEntity entity = response.getEntity();                /** 返回响应的数据 */                return entity.getContent();  //当需要返回为输入流InputStream时的返回值                //return EntityUtils.toString(entity); // 当返回的类型为Json数据时,调用此返回方法            }        } catch (Exception e) {            e.printStackTrace();        }        return null;    }                                                                       /**     * 发送post请求     * @param requestUrl 请求的URL     * @param params 请求的参数     * @return 响应的数据     */    public static InputStream sendPostRequest(String requestUrl, Map<String, String> params){        /** 创建post请求对象 */        HttpPost httpPost = new HttpPost(BASE_URL + requestUrl);        try {            /** 设置请求参数 */            if (params != null && params.size() > 0){                /** 将map转化成list集合 */                List<NameValuePair> paramLists = new ArrayList<NameValuePair>();                for (Map.Entry<String, String> map : params.entrySet()){                    paramLists.add(new BasicNameValuePair(map.getKey(), map.getValue()));                }                /** 为POST请设置请求参数 */                httpPost.setEntity(new UrlEncodedFormEntity(paramLists, "UTF-8"));            }            /** 执行post请求 */            HttpResponse response = httpClient.execute(httpPost);            /** 对响应的状态做判断  */            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){                /** 服务器响应成功 , 获取响应实体*/                HttpEntity entity = response.getEntity();                /** 返回响应数据 */                return entity.getContent();  //当需要返回为输入流InputStream时的返回值                //return EntityUtils.toString(entity);            }        } catch (Exception e) {            System.out.println(BASE_URL + requestUrl);            e.printStackTrace();        }        return null;    }}

当然,基本请求Url BASE_URL 需要我们视情况而定,当我们需要的返回值类型为输入流时
return entity.getContent(); //当需要返回为输入流InputStream时的返回值
当我们需要的返回值类型为Json格式字符串时,我们返回
return EntityUtils.toString(entity); // 当返回的类型为Json数据时,调用此返回方法下面是一个调用的Demo
XML:


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity"    android:orientation="vertical" >    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="连接"        android:onClick="check"/>    <ImageView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:id="@+id/iv"/></LinearLayout>

代码调用:

public void check(View v){            new Thread(){                public void run() {                    InputStream is = HttpUtil.sendGetRequest("");                    Bitmap map = BitmapFactory.decodeStream(is);                    Message msg = Message.obtain();                    msg.obj = map;                    handler.sendMessage(msg);                };            }.start();       }                                  private Handler handler = new Handler(){            public void handleMessage(Message msg) {                iv.setScaleType(ScaleType.FIT_CENTER);                iv.setImageBitmap((Bitmap) msg.obj);            };    };

效果图:wKioL1NsmDXR_LURAAHqu8cF22k713.jpg

当然,本人调用的是HttpUtil.sendGetRequest("")方法,sendPostRequest()方法网络返回状态为400,估计要在项目中或者要自己建立服务器来处理Post请求才可以

更多相关文章

  1. Android去除系统自带动画的两种方法
  2. android studio中建立assets和jnilibs的方法
  3. android查看SQLite数据库linux命令
  4. adb shell 命令查看android 应用程序 创建的 sqlite 数据库
  5. Android unspecified' depends on one or more Android Librarie
  6. Android数据持久化
  7. android控件-ImageView使用方法整理
  8. android的listview 嵌套在 ViewPage 多次调用getview原因和解决
  9. Android提交数据到服务器的两种方式四种方法

随机推荐

  1. Android PendingIntent实现原理和代码
  2. Android照相机模块编程 照片颠倒问题及查
  3. android manifest.xml 标签汇总
  4. android-pull方式解析xml文件以及XML文件
  5. Android学习——android:cacheColorHint=
  6. Android Studio首次运行卡在Fetching and
  7. 一个提供Android各历史版本在线源码的网
  8. 转载——android 有用的知识
  9. Android MVVM之Databinding(二) 使用篇
  10. Android高手进阶教程(七)之----Android