Android--OkHttp

The following get and post are performed in the child thread

get request:

 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 request:

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();
        }

The second parameter is the post request json data upload request. If you do not want to upload this assignment: ""


There is also a need jar package way:

OkHttpUtils use:
in github search OkHttp, which like more clicks which point all right. After pulling Below find the following:
Here Insert Picture Description

The implementation ( "com.squareup.okhttp3: okhttp: 4.4.0") copied into build.gradle files (dependencies inside). And then sync the upper right corner. It can be used.

First understand all the code directly on the later write a detailed point:

    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,"....");
                     }
                 }
             }
         });
     }
}
Published 117 original articles · won praise 1 · views 6989

Guess you like

Origin blog.csdn.net/qq_43616001/article/details/104536748