首先导入jar包
然后写okhttputils
public class OkhttpUtils {
/**
* 通过okhttp的get请求方式获取网络数据
* */
public static String getJsonContent(String url) throws IOException {
// 1.导包 复制jar包---》黏贴到libs文件下---》选中jar包,鼠标右键---》选择Add As Library --》选择ok
// 2.创建客户端对象
OkHttpClient client = new OkHttpClient();
// 3.设置发起请求的对象
Request.Builder builder = new Request.Builder();
Request request = builder.get().url(url).build();
// 4.客户端发起请求,获取响应对象
Response response = client.newCall(request).execute();
// 5.通过响应对象,判断请求是否成功
if (response.isSuccessful()) {
// 6.获得响应体内容
ResponseBody body = response.body();
// 7.获取对应的数据
String msg = body.string();
return msg;
}
return null;
}
/**
* 通过okhttp的post请求方式获取网络数据
**/
public static String postJsonContent(String path, Map<String,String>map){
// 1.导包
// 2.创建客户端对象
OkHttpClient client = new OkHttpClient();
// 获取提交的请求参数
FormBody.Builder builder = new FormBody.Builder();
Set<String> keySet = map.keySet();
for (String key:keySet){
String value = map.get(key);
builder.add(key,value); //向请求体当中添加键值对的过程
}
RequestBody body = builder.build();
// 3.创建请求对象
Request request = new Request.Builder().post(body).url(path).build();
// 4.发起请求,获得响应对象
try {
Response response = client.newCall(request).execute();
// 5.判断请求是否成功
if (response.isSuccessful()) {
// 6.获得请求体内容
ResponseBody responseBody = response.body();
String msg = responseBody.string();
return msg;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
然后在MainActivity的代码
public class MainActivity extends AppCompatActivity {
private TextView tv;
private String url = "http://218.244.149.129:9010/api/companylist.php?industryid=98";
private String postUrl = "http://218.244.149.129:9010/api/companylist.php";
private String body = "industryid=98";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv);
new MyAsycnTask().execute(url);
}
class MyAsycnTask extends AsyncTask<String,Void,String>{
@Override
protected String doInBackground(String... params) {
// String content = ConnectionUtils.postJsonContent(params[0], body);
/* Map<String,String>map = new HashMap<>();
map.put("industryid","98");
String content = null;
try {
content = ClientUtils.postJsonContent(params[0],map);
} catch (IOException e) {
e.printStackTrace();
}*/
String content = "";
try {
content = OkhttpUtils.getJsonContent(params[0]);
} catch (IOException e) {
e.printStackTrace();
}
return content;
}
@Override
protected void onPostExecute(String s) {
if (s!=null&&!s.isEmpty()) {
tv.setText(s);
}
}
}
}