首页 > 代码库 > Okhttp3的简单使用
Okhttp3的简单使用
1.get请求:
/** * *okhttp get请求 * */ public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /** * 创建okhttpClient对象 * */ OkHttpClient mOkHttpClient = new OkHttpClient(); /** *创建Request对象 **/ final Request request = new Request.Builder() .url("http://v.juhe.cn/toutiao/index?type=top&key=3f8238bb55566d2b3f0d2204a5e9631f") .build(); /** * new Call * */ Call call = mOkHttpClient.newCall(request); /** * 请求调度 * */ call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e(TAG, "onFailure: "+e.toString()); } @Override public void onResponse(Call call, Response response) throws IOException { String htmlStr = response.body().string(); Log.d(TAG, "onResponse() called with: " + "call = [" + call + "], response = [" + htmlStr + "]"); } }); } }
2,post请求:
/** * * okhttp post请求 * */ public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; /** * 请求地址 * */ String URL = "这里为请求地址"; JSONObject obj = new JSONObject(); String sss; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /** * post请求体为json字符串 * */ try { obj.put("name", "123"); obj.put("pwd", "456"); sss = obj.toString(); post(URL, sss); } catch (Exception e) { e.printStackTrace(); } } public void post(String url, String json) throws IOException { OkHttpClient client = new OkHttpClient(); MediaType JSON = MediaType.parse("application/json; charset=utf-8"); RequestBody body = RequestBody.create(JSON, json); Request request = new Request.Builder().url(url).post(body).build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e(TAG, "onFailure: "+e.toString() ); } @Override public void onResponse(Call call, Response response) throws IOException { Log.i(TAG, "onResponse*: "+response.body().string()); } }); } }
Okhttp3的简单使用
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。