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();
    }
});
 
 
 
 
                    
                 
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号