android使用OKHttp完成的查询号码归属地示例

OKHttp下载地址:http://square.github.io/okhttp/#download
OKhttp的四个步骤:
1.得到okHttpClient对象
2.构造Request
3.将Request封装位Call
4.执行call

MainActivity:

package com.example.apple.myapplication;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.zph.impl.MainPresenter;
import com.zph.phone.Phone;
import com.zph.view.MvpMainView;

public class MainActivity extends AppCompatActivity implements View.OnClickListener,MvpMainView{


    EditText input_phone;
    Button btn_search;
    TextView result_phone;
    TextView result_provice;
    TextView result_boss;
    TextView result_bossprovice;
    MainPresenter mainPresenter;
    ProgressDialog progressDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        input_phone = (EditText) findViewById(R.id.input_phone);
        result_phone = (TextView) findViewById(R.id.result_phone);
        result_provice = (TextView) findViewById(R.id.result_provice);
        result_boss = (TextView) findViewById(R.id.result_Type);
        result_bossprovice = (TextView) findViewById(R.id.result_carrier);
        btn_search = (Button)findViewById(R.id.btn_search);
        btn_search.setOnClickListener(this);
        mainPresenter = new MainPresenter(this);
        mainPresenter.attach(this);
    }

    public void onClick(View view) {       mainPresenter.searchPhoneInfo(input_phone.getText().toString());
    }
    //mainmvpview接口的方法
    public void showLoading() {

        if(progressDialog == null)
        {
            progressDialog = ProgressDialog.show(this,"","正在加载...",true,false);
        }else  if(progressDialog.isShowing())
        {
            progressDialog.setTitle("");
            progressDialog.setMessage("正在加载...");
        }
        progressDialog.show();
    }
    public void hideLoading() {

        if(progressDialog != null && progressDialog.isShowing())
        {
            progressDialog.dismiss();
        }
    }
    public void showToast(String msg) {

        Toast.makeText(this,msg, Toast.LENGTH_LONG).show();
    }
    public void updateView() {

        Phone phone = mainPresenter.getPhoneInfo();
        result_phone.setText("手机号码:"+phone.getPhone().toString());
        result_provice.setText("省份:"+phone.getProvince().toString());
        result_boss.setText("运营商:"+phone.getType().toString());
        result_bossprovice.setText("运营商归属地:"+phone.getCarrier().toString());
    }
}

HttpUntil:
``
package com.zph.business;
import android.os.Handler;
import android.os.Looper;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/**
 * Created by apple on 17-8-11.
 */
public class HttpUntil {
    String mUrl;
    Map<String,String> mParam;
    HttpResponse mHttpResponse;
    Handler myHandler = new Handler(Looper.getMainLooper());
    OkHttpClient client;
    MultipartBody.Builder requestBodyBuilder;
    public interface HttpResponse
    {
        void onSuccess(Object object);
        void onFail(String error);

    }
    public HttpUntil(HttpResponse mHttpResponse)
    {
        this.mHttpResponse = mHttpResponse;
    }
    public void sendPostHttp(String url, Map<String,String> param)
    {
        sendHttp(url,param,true);
    }
    public void sendGetHttp(String url,Map<String,String> param)
    {
        sendHttp(url,param,false);
    }
    private  void sendHttp(String url,Map<String,String> param,boolean isPost)
    {
        mUrl = url;
        mParam = param;
        //编写http请求逻辑
        run(isPost);
    }
    private void run(boolean isPost)
    {
        //request请求创建
        Request request = createRequest(isPost);
        //创建请求队列
        client  = new OkHttpClient();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if(mHttpResponse != null)
                {

                    myHandler.post(new Runnable()
                    {

                        @Override
                        public void run() {
                            mHttpResponse.onFail("请求错误");
                        }
                    });
                }
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {

                 if(mHttpResponse == null)
                 {
                     return;
                 }
                    myHandler.post(new Runnable() {
                         @Override
                         public void run() {
                             if(!response.isSuccessful())
                             {
                                 mHttpResponse.onFail("请求失败:code"+response);
                             }else {
                                 try {
                                     mHttpResponse.onSuccess(response.body().string());  //有问题
                                 } catch (IOException e) {
                                     e.printStackTrace();
                                     mHttpResponse.onFail("结果转换失败:code"+response);
                                 }

                             }
                         }
                     });
                 }
        });

    }
    private Request createRequest(boolean isPost)
    {
        Request request;
        if(isPost)
        {
            requestBodyBuilder = new MultipartBody.Builder();
            requestBodyBuilder.setType(MultipartBody.FORM);
            //遍历map请求参数
            Iterator<Map.Entry<String,String>> iterator = mParam.entrySet().iterator();

            while((iterator.hasNext()))
            {
                Map.Entry<String,String>entry = iterator.next();
                requestBodyBuilder.addFormDataPart(entry.getKey(),entry.getValue());

            }
            request = new okhttp3.Request.Builder().url(mUrl)
                    .post(requestBodyBuilder.build()).build();
        }else{

            String urlStr = mUrl+"?"+MapParamToString(mParam);
            request = new okhttp3.Request.Builder().url(urlStr)
                    .build();
        }
        return  request;
    }
    private String MapParamToString(Map<String,String>param)
    {
        StringBuilder stringBuilder = new StringBuilder();
        Iterator<Map.Entry<String,String>>iterator = param.entrySet().iterator();
        while (iterator.hasNext())
        {
            Map.Entry<String,String>entry = iterator.next();
            stringBuilder.append(entry.getKey()+"="+entry.getValue()+"&");
        }
        String str = stringBuilder.toString().substring(0,stringBuilder.length()-1);
        return str;
    }
}

具体代码下载:http://download.csdn.net/download/zph321/9934771

这里写图片描述
h

猜你喜欢

转载自blog.csdn.net/zph321/article/details/77196851