java 利用okhttp发送网络请求

android网络框架之OKhttp[1]一个处理网络请求的开源项目,是安卓端最火热的轻量级框架,由移动支付[Squar(http://baike.baidu.com/item/Square/65870)公司贡献(该公司还贡献了Picasso)[2]用于替代HttpUrlConnection和Apache HttpClient(android API23 6.0里已移除HttpClient,现在已经打不出来)

下载地址:okhttp ,要翻墙下载,必须下载okhttp以及okio两个jar包。

示例代码:

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 利用okhtto实现发送网络请求
 * @author zhaotong
 *
 */
public class ServiceTools {

    public static final MediaType JSON= MediaType.parse("application/json; charset=utf-8");
    
    private static OkHttpClient client=new OkHttpClient();
    
    //发送post请求
    public static String postTargetData(String  url ,String content )
    {
        String result=null;
        RequestBody body=RequestBody.create(JSON,content);
        Request request=new Request.Builder().url(url).post(body).build();
        Response res=null;
        try {
            res = client.newCall(request).execute();
            result=res.body().string();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return result; 
    }
    //发送get请求
    public static String getTargetData(String url)
    {
        String result=null;
        Request request=new Request.Builder().url(url).build();
        Response res=null;
        try {
            res=client.newCall(request).execute();
            result=res.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容