java okHttp基础

java okHttp基础

使用eclipse时,我们需要导入okhttp的jar包和OKio的jar包,即OkHttp在底层使用Okio,所 以,如果不使用Maven等方式 自动导入到项目中,就必须单独下载Okio组件。

okhttp jar包

okio jar包

下载之后,放在eclipse项目的lib文件夹下,再将它们加入到项目的Build Path中,就可以 使用okhttp了。如图:

这里写图片描述

get方法示例:

import java.io.*;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class TestMain {

    private static String url="http://39.106.10.62/wp-content/uploads/2018/08/t1.html";


    public static void main(String[] args){
        doGet1();
        doGet2();
    }

    public static void doGet1(){
        OkHttpClient client=new OkHttpClient();
        Request.Builder builder=new Request.Builder();
        Request request=builder.get().url(url).build();

        Call call=client.newCall(request);

        call.enqueue(new Callback(){

            @Override
            public void onFailure(Call arg0, IOException arg1) {
                // TODO Auto-generated method stub
                System.out.println(arg1.getMessage());
            }

            @Override
            public void onResponse(Call arg0, Response arg1) throws IOException {
                // TODO Auto-generated method stub
                System.out.println(arg1.body().string());
            }

        });
    }

    public static void doGet2(){
        OkHttpClient client=new OkHttpClient();
        Request request=new Request.Builder()
                .url(url)
                .build();

        try(Response response=client.newCall(request).execute()){
            System.out.println(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

POST请求示例:

import java.io.*;

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

public class TestMain {

    //金老师的网站四则运算API
    private static String url="http://jinxuliang.com/OpenService/api/OnlineCalculator/Calculate";

    public static void main(String[] args){
        doPost1();
        doPost2();
    }

    public static void doPost1(){
        String expression="6+3*2";
        OkHttpClient client=new OkHttpClient();
        Request.Builder builder=new Request.Builder();

        String json="{expr:'"+expression+"'}";
        RequestBody body=RequestBody.create(MediaType.parse("application/json"), json);

        Request request=builder.url(url).post(body).build();
        Call call=client.newCall(request);

        call.enqueue(new Callback() {

            @Override
            public void onResponse(Call arg0, Response arg1) throws IOException {
                // TODO Auto-generated method stub
                String result=arg1.body().string();
                System.out.println(result);
            }

            @Override
            public void onFailure(Call arg0, IOException arg1) {
                // TODO Auto-generated method stub
                System.out.println(arg1.getMessage());
            }
        });
    }

    public static void doPost2(){
        String expression="6+3*2";
        String json="{expr:'"+expression+"'}";
        RequestBody body=RequestBody.create(MediaType.parse("application/json"), json);

        OkHttpClient client=new OkHttpClient();
        Request request=new Request.Builder()
                .url(url)
                .post(body)
                .build();

        try(Response response=client.newCall(request).execute()){
            String result=response.body().string();
            System.out.println(result);
        }catch(IOException e){
            e.printStackTrace();
        }
    }

}

从金老师网站下载图片:


import java.io.*;

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

public class TestMain {

    //金老师的网站四则运算API
    private static String url="http://jinxuliang.com/book/api/bookservice/GetCoverById/59da0dd1a664d711482b9606";

    public static void main(String[] args){
//      downloadImg1();
        downloadImg2();
    }

    public static void downloadImg1(){
        OkHttpClient client=new OkHttpClient();
        Request.Builder builder=new Request.Builder();
        Request request=builder.url(url).build();
        Call call=client.newCall(request);
        call.enqueue(new Callback() {

            @Override
            public void onResponse(Call arg0, Response arg1) throws IOException {
                // TODO Auto-generated method stub
                InputStream iStream=arg1.body().byteStream();
                int len=0;
                File file=new File("test1.jpg");
                FileOutputStream fileOutputStream=new FileOutputStream(file);
                byte[] buf=new byte[2048];
                while((len=iStream.read(buf))>0){
                    fileOutputStream.write(buf, 0, len);
                }
                fileOutputStream.flush();
                fileOutputStream.close();
                iStream.close();
                System.out.println("download finished!");
            }

            @Override
            public void onFailure(Call arg0, IOException arg1) {
                // TODO Auto-generated method stub
                System.out.println(arg1.getMessage());
            }
        });
    }

    public static void downloadImg2() {
        OkHttpClient client=new OkHttpClient();
        Request request=new Request.Builder()
                .url(url)
                .build();
        try(Response response=client.newCall(request).execute()){
            InputStream iStream=response.body().byteStream();
            int len=0;
            File file=new File("test2.jpg");
            FileOutputStream fileOutputStream=new FileOutputStream(file);
            byte[] buf=new byte[2048];
            while((len=iStream.read(buf))>0){
                fileOutputStream.write(buf, 0, len);
            }
            fileOutputStream.flush();
            fileOutputStream.close();
            iStream.close();
            System.out.println("download finished!");
        }catch(IOException e){
            e.printStackTrace();
        }
    }
}

下载的图片在文件资源管理器项目路径下可看到。

更多参考:

http://square.github.io/okhttp/3.x/okhttp/

参考:

金旭亮Java编程系列

http://square.github.io/okhttp/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值