android HttpClient get请求与post请求工具类

来源:互联网 发布:网络商店需要哪些手续 编辑:程序博客网 时间:2024/05/29 13:40

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

package com.example.httpnetwork;import java.io.InputStream;import java.util.ArrayList;import java.util.List;import java.util.Map;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);
        };
};


效果图:


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

0 0