Android--OkHttp

下面的get和post都必须在子线程中执行

get请求:

 private OkHttpClient client = new OkHttpClient();
	
 String get(String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .build();
        Response response = client.newCall(request).execute();
            return response.body().string();

    }

post请求:

private OkHttpClient client = new OkHttpClient();
public static final MediaType JSON
            = MediaType.parse("application/json; charset=utf-8");

    String post(String url, String json) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Response response = client.newCall(request).execute();
        return response.body().string();
        }

post请求第二个参数是请求的上传的json数据。如果没有要上传这赋值:“”


还有一种不用jar包的方式:

OkHttpUtils的使用:
在github搜索OkHttp,哪个点赞多点击哪个好吧。之后拉到下面找到下面这个:
Android--OkHttp

将 implementation(“com.squareup.okhttp3:okhttp:4.4.0”) 复制进 build.gradle文件(dependencies 里面)。然后进行右上角的同步。即可是使用了。

直接上全部代码先理解着,以后再写详细点:

    private static final String PATH ="http://192.168.137.1:8080/cookie_war_exploded/ShopInfoServlet" ;
     private static final String TAG="okhttp";

     @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }


	//get,返回数据
    public void getRequest(View view){

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10000, TimeUnit.MILLISECONDS)
                .build();
        //创建连接请求内容
        Request request=new Request.Builder()
                .get()
                .url(PATH)
                .build();
        //用Client去创建请求任务
        Call task=okHttpClient.newCall(request);
        //异步任务
        task.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.e(TAG," onFailure:"+e.toString());
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                int code = response.code();
                if(code== HttpURLConnection.HTTP_OK){
                    Log.e(TAG,"code:"+code);
                    ResponseBody body = response.body();
                    Log.e(TAG,"onResponse   :"+body.string());
                }
            }
        });
    }

	//post,返回数据
     public void postCommit(View view){
         //先有CLient
         OkHttpClient client=new OkHttpClient.Builder()
                 .connectTimeout(10000,TimeUnit.MILLISECONDS)
                 .build();


         //要提交的内容
         String str="在吗";
         str=new Gson().toJson(str);
         MediaType mediaType=MediaType.parse("application/json");

         RequestBody body=RequestBody.create(str,mediaType);

         final Request request=new Request.Builder()
                 .post(body)
                 .url(PATH)
                 .build();

         Call task=client.newCall(request);
         task.enqueue(new Callback() {
             @Override
             public void onFailure(@NotNull Call call, @NotNull IOException e) {
                 Log.e(TAG,"onFailure"+e.toString());
             }

             @Override
             public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                 int code = response.code();
                 ResponseBody responseBody = response.body();
                 Log.e(TAG,"onResponse"+code+"----"+responseBody.string());
             }
         });
     }




     //上传文件到服务器。由于我没做过服务器来接收文件。所以这里先写个代码记录下。等下次会了再回来写详细点
     public void postFile(View view){

         OkHttpClient client=new OkHttpClient.Builder()
                 .connectTimeout(10000,TimeUnit.MILLISECONDS)
                 .build();

         File file=new File("/data/data/com.example.mybitmap/files/qq.jpg");

         MediaType fileType=MediaType.parse("image/png");
         RequestBody fileBody=RequestBody.create(file,fileType);

         final RequestBody requestBody = new MultipartBody.Builder()
                 .addFormDataPart("file",file.getName(),fileBody)
                 .build();

         Request request=new Request.Builder()
                 .post(requestBody)
                 .url(PATH)
                 .build();

         Call task=client.newCall(request);
         task.enqueue(new Callback() {
             @Override
             public void onFailure(@NotNull Call call, @NotNull IOException e) {
                 Log.e(TAG,"....");
             }

             @Override
             public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                 Log.e(TAG,"....");
                 if((response.code()==HttpURLConnection.HTTP_OK)){
                     ResponseBody body=response.body();
                     if(body!=null){
                         String result=body.string();
                         Log.e(TAG,"....");
                     }
                 }
             }
         });
     }
}
Android--OkHttpAndroid--OkHttp 啊翔仔 发布了117 篇原创文章 · 获赞 1 · 访问量 6987 私信 关注
上一篇:Gauss消元法的原理及Java实现


下一篇:OkHttp 源码解析(一)