OkHttp网络请求框架

添加依赖方式见

https://blog.csdn.net/weimeig/article/details/78656734

创建menu方式见

https://blog.csdn.net/weimeig/article/details/79712595

一、Get请求

创建menu

action.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:title="Get" android:id="@+id/menuGet" />
    <item android:id="@+id/menuResponse" android:title="Response" />
    <item android:id="@+id/menuPost" android:title="post" />
</menu>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.administrator.picassodemo.MainActivity">


    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
        android:id="@+id/tvContent"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />
    </ScrollView>


</android.support.constraint.ConstraintLayout>

MainActivity.java

package com.administrator.picassodemo;

import android.media.Image;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

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


public class MainActivity extends AppCompatActivity {

    private TextView mTextView;
    private OkHttpClient mClient;
    private static final String TAG = "MainActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextView = (TextView)findViewById(R.id.tvContent);


        mClient = new OkHttpClient();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.action,menu);

        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.menuGet:
                get();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void get() {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.submit(new Runnable() {
            @Override
            public void run() {

//                -------------------------------
                Request.Builder builder = new Request.Builder();
                builder.url("https://raw.githubusercontent.com/square/okhttp/master/README.md");
                Request request = builder.build();
                Log.d(TAG, "run: " + request);
                Call call = mClient.newCall(request);
                try {
                    Response response = call.execute();
                    if (response.isSuccessful()) {
                        final String string = response.body().string();
//                        --------
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mTextView.setText(string);
                            }
                        });
//                        --------
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
//                -------------------------------


            }
        });
        executor.shutdown();
    }
}

二、get-Response

 private void respsonse() {
        Request request = new Request.Builder()
                .url("https://raw.githubusercontent.com/square/okhttp/master/README.md")
                .build();

        Call call = mClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG,"onFailure() called with:call=[" +call +"],e=["+ e +"]");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG,"onResponse() called with:call=[" +call +"],response=["+ response +"]");
                int code = response.code();
                Headers headers = response.headers();
                String content = response.body().string();
                String contentType = headers.get("Content-Type");
                final StringBuilder buf = new StringBuilder();
                buf.append("code"+code);
                buf.append("\nHeaders"+headers);
                buf.append("\nBody"+content);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mTextView.setText(buf.toString());
                    }
                });
            }
        });
    }

三、Post请求

private void respsonse() {
        Request request = new Request.Builder()
                .url("https://raw.githubusercontent.com/square/okhttp/master/README.md")
                .build();

        Call call = mClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG,"onFailure() called with:call=[" +call +"],e=["+ e +"]");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG,"onResponse() called with:call=[" +call +"],response=["+ response +"]");
                int code = response.code();
                Headers headers = response.headers();
                String content = response.body().string();
                String contentType = headers.get("Content-Type");
                final StringBuilder buf = new StringBuilder();
                buf.append("code"+code);
                buf.append("\nHeaders"+headers);
                buf.append("\nBody"+content);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mTextView.setText(buf.toString());
                    }
                });
            }
        });
    }

MainActivity完整代码

MainActivity.java

package com.administrator.picassodemo;

import android.media.Image;
import android.preference.PreferenceActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.IOException;
import java.time.LocalDate;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

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


public class MainActivity extends AppCompatActivity {

    private TextView mTextView;
    private OkHttpClient mClient;
    private static final String TAG = "MainActivity";
    private static final MediaType MEDIA_TYPE_MARKDOWN
            = MediaType.parse("text/x-markdown; charset=utf-8");
    private static final String POST_URL = "https://api.github.com/markdown/raw";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextView = (TextView)findViewById(R.id.tvContent);


        mClient = new OkHttpClient();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.action,menu);

        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.menuGet:
                get();
                break;
            case R.id.menuResponse:
                respsonse();
                break;
            case R.id.menuPost:
                post();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void respsonse() {
        Request request = new Request.Builder()
                .url("https://raw.githubusercontent.com/square/okhttp/master/README.md")
                .build();

        Call call = mClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG,"onFailure() called with:call=[" +call +"],e=["+ e +"]");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG,"onResponse() called with:call=[" +call +"],response=["+ response +"]");
                int code = response.code();
                Headers headers = response.headers();
                String content = response.body().string();
                String contentType = headers.get("Content-Type");
                final StringBuilder buf = new StringBuilder();
                buf.append("code"+code);
                buf.append("\nHeaders"+headers);
                buf.append("\nBody"+content);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mTextView.setText(buf.toString());
                    }
                });
            }
        });
    }

    private void get() {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.submit(new Runnable() {
            @Override
            public void run() {

//                -------------------------------
                Request.Builder builder = new Request.Builder();
                builder.url("https://raw.githubusercontent.com/square/okhttp/master/README.md");
                Request request = builder.build();
                Log.d(TAG, "run: " + request);
                Call call = mClient.newCall(request);
                try {
                    Response response = call.execute();
                    if (response.isSuccessful()) {
                        final String string = response.body().string();
//                        --------
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mTextView.setText(string);
                            }
                        });
//                        --------
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
//                -------------------------------


            }
        });
        executor.shutdown();
    }

    private void post(){
        Request.Builder builder = new Request.Builder()
                .url(POST_URL)
                .post(RequestBody.create(MEDIA_TYPE_MARKDOWN,"Hello world github/linguist#1 **cool**, and #1!"));
        Request request = builder.build();
        Call call = mClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(response.isSuccessful()){
                    final String content = response.body().string();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mTextView.setText(content);
                        }
                    });
                }
            }
        });

    }
}

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页