okhttp的使用以及 post json进行请求数据

  • Post author:
  • Post category:其他


一、在build.gradlet添加

compile ‘com.squareup.okhttp3:okhttp:3.8.1’

compile ‘com.squareup.okio:okio:1.13.0’

二、添加使用权限

<uses-permission android:name=”android.permission.ACCESS_WIFI_STATE” />

<uses-permission android:name=”android.permission.INTERNET” />

<uses-permission android:name=”android.permission.READ_EXTERNAL_STORAGE” />

<uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE” />

三、建一个简单的请求工具类

import android.os.Handler;

import android.os.Message;

import android.util.Log;

import com.google.gson.Gson;

import com.google.gson.GsonBuilder;

import java.io.IOException;

import java.util.Map;

import okhttp3.MediaType;

import okhttp3.OkHttpClient;

import okhttp3.Request;

import okhttp3.RequestBody;

import okhttp3.Response;

/**

* Created by admin on 2018/4/25.

*/

public class OkHttpUtils {

private static final String TAG = OkHttpUtils.class.getSimpleName();

public static final MediaType JSON

= MediaType.parse(“application/json; charset=utf-8”);

private static final int GET = 1;

private static final int POSTJSON = 2;

private OkHttpClient client = new OkHttpClient();

private static OkHttpUtils instance;

private OkHttpUtils(){


}

public static OkHttpUtils getInstance(){


if (instance == null){


instance = new OkHttpUtils();

}

return instance;

}

private Handler handler = new Handler() {


@Override

public void handleMessage(Message msg) {


super.handleMessage(msg);

switch (msg.what) {


case GET:

Log.i(TAG,”GET—->”+(String) msg.obj);

break;

case POSTJSON:

Log.i(TAG, “POSTJSON—->”+(String) msg.obj + msg.arg1);

break;

}

}

};

/**

*

* @param url 请求地址

* @return

* @throws IOException

*/

private String get(String url) throws IOException {


Request request = new Request.Builder().url(url).build();

Response response = client.newCall(request).execute();

return response.body().string();

}

/**

*

* @param url 请求地址

* @param json json字符串请求参数

* @return

* @throws IOException

*/

public String postJson(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();

//response.body().string()这一句代码在方法体里面只能用一次(包括打印输出的使用)

return response.body().string();

}

/**

* @param url  请求地址

*/

public void requestDataFromeGet(final String url) {


new Thread() {


@Override

public void run() {


super.run();

try {


String result = get(url);

Message message = Message.obtain();

message.what = GET;

message.obj = result;

handler.sendMessage(message);

} catch (IOException e) {


e.printStackTrace();

}

}

}.start();

}

/**

*

* @param url 请求地址

* @param map 请求参数(把map转换成gson)

*/

public void rquestDataFromePostJson(final String url, final Map<String, Object> map) {


new Thread(){


@Override

public void run() {


super.run();

try {


//Map转JSON数据

Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();

String result = postJson(url, gson.toJson(map));

Log.i(TAG,gson.toJson(map));

Message message = Message.obtain();

message.what = POSTJSON;

message.obj = result;

handler.sendMessage(message);

} catch (IOException e) {


e.printStackTrace();

}

}

}.start();

}

}

四、简单的调用

import android.content.Context;

import android.net.wifi.WifiInfo;

import android.net.wifi.WifiManager;

import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

import com.example.admin.currentdatetime.utils.OkHttpUtils;

import java.net.Inet4Address;

import java.net.InetAddress;

import java.net.NetworkInterface;

import java.net.SocketException;

import java.util.Enumeration;

import java.util.HashMap;

import java.util.Map;

public class OkHttpActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);

setContentView(R.layout.activity_ok_http);

OkHttpUtils okHttpUtils = OkHttpUtils.getInstance();

okHttpUtils.requestDataFromeGet(“http://www.baidu.com”);

final Map<String, Object> map = new HashMap<>();

map.put(“machine_mac”, getMacAddress(this));

map.put(“machine_ip”, getIPAddress());

map.put(“win_num”, “0033”);

okHttpUtils.rquestDataFromePostJson(“https://”, map);

}

//获取MAC地址

public String getMacAddress(Context context) {


WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

WifiInfo info = wifi.getConnectionInfo();

return info.getMacAddress();

}

//获取IP地址

public static String getIPAddress() {

try {


for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {


NetworkInterface intf = en.nextElement();

for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {


InetAddress inetAddress = enumIpAddr.nextElement();

if (!inetAddress.isLoopbackAddress() && (inetAddress instanceof Inet4Address)) {


return inetAddress.getHostAddress().toString();

}

}

}

} catch (SocketException ex) {


ex.printStackTrace();

}

return null;

}

}

五、OkHttp使用的一些小坑

1、如果把get方法或者postJson的方法里面的response.body().string();写成response.body().toString();

返回的不是数据而是实例化对象okhttp3.internal.http.RealResponseBody@419a38380

2、response.body().string();只能使用一次。不然会报一个错误如下

为了方便使用进行Okhttp的二次封装:

https://blog.csdn.net/u011905195/article/details/85333049



版权声明:本文为u011905195原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。