android中怎么实现HttpClient get请求与post请求

发布时间:2021-06-28 18:26:48 作者:Leah
来源:亿速云 阅读:199

android中怎么实现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);
            };
    };

关于android中怎么实现HttpClient get请求与post请求问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

推荐阅读:
  1. 如何用spring-boot集成httpClient实现远程调用
  2. Spring+Http请求+HttpClient实现传参

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

post get httpclient

上一篇:Android中怎么自定义一个环形LoadingView效果

下一篇:Android中怎么使用ViewPager实现左右循环滑动效果

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》