Android中OKHttp框架的使用

本文介绍了一个使用OkHttp实现的网络请求工具类,对比了使用OkHttp与Httpclient等传统方式的区别,提供了完整的示例代码,展示了如何通过OkHttp进行POST请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//使用okhttp代替了 Httpclient,Httpuricotion,使用该框架请求网络,是谷歌推出的最新的一款技术,今天在这里展示

这是一个工具类,直接调用就可以了
这个请求,需要一个Jar包

package com.example.utils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

public class HttpTool {
    protected static final String TAG = "HttpTool";
    // http://169.254.61.202:8080/MyPaoT/register
    private String result = null;

    public String doPost(final String url, final Map<String, String> map,
            final String charset) {

        new Thread() {

            public void run() {

                HttpClient httpClient = null;
                HttpPost httpPost = null;

                try {
                    httpClient = new DefaultHttpClient();
                    httpPost = new HttpPost(url);

                    List<NameValuePair> list = new ArrayList<NameValuePair>();
                    Iterator iterator = map.entrySet().iterator();
                    while (iterator.hasNext()) {
                        Entry<String, String> elem = (Entry<String, String>) iterator
                                .next();
                        list.add(new BasicNameValuePair(elem.getKey(), elem
                                .getValue()));
                    }
                    if (list.size() > 0) {
                        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(
                                list, charset);
                        httpPost.setEntity(entity);
                    }
                    HttpResponse response = httpClient.execute(httpPost);
                    if (response != null) {
                        HttpEntity resEntity = response.getEntity();
                        if (resEntity != null) {
                            result = EntityUtils.toString(resEntity, charset);
                            Log.i(TAG, "-HttpTool这里是 是否注册成功" + result);
                        }
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }

            };
        }.start();
        return result;
    }
 /**
  *     OKHttp
  * @param url
  * @param map
  * @return
  */
    public static String post(final String url, final Map<String, String> map) {
        OkHttpClient client = new OkHttpClient();

        FormEncodingBuilder formBody = new FormEncodingBuilder();
        Iterator it = map.entrySet().iterator();
        System.out.println(map.entrySet().size());
        String key;
        String value;
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            key = entry.getKey().toString();
            value = entry.getValue().toString();
            formBody.add(key, value);

//          System.out.println(key + "====" + value);
            Log.i(TAG, "@@@@@");
        }
        Request request = new Request.Builder().url(url).post(formBody.build())
                .build();
        Log.i(TAG, request+"====request===");
        Response response = null;
        try {
            response = client.newCall(request).execute();
             Log.i(TAG, response+"====response===");
            String string = response.body().string();
             Log.i(TAG, string+"====string===");
            if (string!=null) {

                return string;

            }else{
                 Log.i(TAG, string+"=======");
            }



        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
### 关于 Android 开发中 OkHttp 框架使用 #### 简介 OkHttp 是一个用于发起网络请求的开源项目,作为 Android 平台上的轻量级框架,它不仅支持文件上传与下载功能,还兼容 HTTPS 协议[^1]。 #### 使用方法概述 为了在应用程序中利用 OkHttp 执行 HTTP 请求,开发者需遵循几个基本步骤来设置环境并编写相应的代码逻辑。这包括但不限于引入必要的依赖库以及实现具体的同步或异步 POST/GET 请求操作[^3]。 #### 实现简单的 GET 请求 下面展示了一个通过 OkHttp 客户端发送 GET 请求的具体实例: ```java import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class Example { public static void main(String[] args) throws Exception { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("https://www.example.com") .build(); try (Response response = client.newCall(request).execute()) { if (!response.isSuccessful()) throw new RuntimeException("Unexpected code " + response); System.out.println(response.body().string()); } } } ``` 此段代码展示了如何创建 `OkHttpClient` 对象,并构建一个新的 `Request` 来指定目标 URL 和请求方式(这里是 GET)。接着调用了 `.newCall()` 方法执行该请求,并处理返回的数据流[^4]。 #### 更多高级特性 除了基础的功能外,OkHttp 提供了许多其他有用的特性和配置选项,比如连接池管理、缓存机制等,这些都可以显著提高应用性能和用户体验。对于更复杂的场景,则可以考虑采用像 Retrofit 这样的更高层次抽象工具来进行 API 调用和服务接口定义。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值