首页 > 代码库 > Android 中OKHttp请求数据get和post
Android 中OKHttp请求数据get和post
1:在Android Studio 的 build.gradle下 添加 然后再同步一下
compile ‘com.squareup.okhttp:okhttp:2.4.0‘
compile ‘com.squareup.okio:okio:1.5.0‘
compile ‘junit:junit:4.12‘
如:黄色部分
dependencies {
compile fileTree(include: [‘*.jar‘], dir: ‘libs‘)
testCompile ‘junit:junit:4.12‘
compile ‘com.android.support:appcompat-v7:23.4.0‘
compile ‘com.github.bumptech.glide:glide:3.6.1‘
compile files(‘libs/gson-2.2.4.jar‘)
compile ‘com.squareup.okhttp:okhttp:2.4.0‘
compile ‘com.squareup.okio:okio:1.5.0‘
compile ‘junit:junit:4.12‘
}
2:get请求
如:
/**
* OkHttpClient 的Get请求
*/
//创建okHttpClient对象
OkHttpClient mOkHttpClient = new OkHttpClient();
//创建一个Request
final Request request = new Request.Builder()
.url("http://m.yunifang.com/yunifang/mobile/goods/getall?random=97575&encode=f1c61556b05c0cf193e74b1e8fc6420c&category_id=17")
.build();
//new call
Call call = mOkHttpClient.newCall(request);
//请求加入调度
call.enqueue(new Callback()
{
@Override
public void onFailure(Request request, IOException e)
{
}
@Override
public void onResponse(final Response response) throws IOException
{
String htmlStr = response.body().string();
Log.i("kkkkkkkkkkkkk",htmlStr);
}
});
3:post请求 注意:有的接口不支持post请求
如:
/**
* OKHttp Post请求
*/
//创建okHttpClient对象
OkHttpClient mOkHttpClient = new OkHttpClient();
FormEncodingBuilder builder = new FormEncodingBuilder();
builder.add("random","97575");
builder.add("encode","f1c61556b05c0cf193e74b1e8fc6420c");
builder.add("category_id","17");
//创建一个Request
//http://www.yulin520.com/a2a/impressApi/news/mergeList?sign=C7548DE604BCB8A17592EFB9006F9265&pageSize=10&gender=2&ts=1871746850&page=1
//http://m.yunifang.com/yunifang/mobile/goods/getall?random=97575&encode=f1c61556b05c0cf193e74b1e8fc6420c&category_id=17
final Request request = new Request.Builder()
.url("http://m.yunifang.com/yunifang/mobile/goods/getall")
.post(builder.build()).build();
//new call
Call call = mOkHttpClient.newCall(request);
//请求加入调度
call.enqueue(new Callback()
{
@Override
public void onFailure(Request request, IOException e)
{
// Toast.makeText(MainActivity.this,"请求失败",Toast.LENGTH_SHORT).show();
}
@Override
public void onResponse(final Response response) throws IOException
{
String htmlStr = response.body().string();
Log.i("htmlStr---",htmlStr);
Gson gson=new Gson();
Gods gods=gson.fromJson(htmlStr,Gods.class);
databean=gods.getData();
if (adapter==null){
adapter=new MyAdapter(databean,MainActivity.this);
gv.setAdapter(adapter);
}
adapter.notifyDataSetChanged();
}
});
Android 中OKHttp请求数据get和post
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。