package com.example.gsc.xinkongjian; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; import com.squareup.okhttp.ResponseBody; import java.io.IOException; import retrofit.Call; import retrofit.Callback; import retrofit.Response; import retrofit.Retrofit; /** * Created by Administrator on 2016/7/25. */ public class TestNetActivity extends Activity { private TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_t); tv= (TextView) findViewById(R.id.tv); } public void get(View v){ Retrofit retrofit = new Retrofit.Builder().baseUrl("http://www.baidu.com/").build(); Itest getBaidu = retrofit.create(Itest.class);//使用上面声明的接口创建 Call<ResponseBody> call = getBaidu.get();//获取一个Call,才可以执行请求 //异步请求.... call.enqueue(new Callback<ResponseBody>() {//异步 @Override public void onResponse(Response<ResponseBody> response, Retrofit retrofit) { try { String body = response.body().string();//获取返回体的字符串 System.out.println("当前线程:"+Thread.currentThread().getName());//是Main线程 tv.setText(body); } catch (IOException e) { e.printStackTrace(); } } @Override public void onFailure(Throwable t) { } }); } }
package com.example.gsc.xinkongjian; import com.squareup.okhttp.ResponseBody; import retrofit.Call; import retrofit.http.GET; /** * Created by Administrator on 2016/7/25. */ public interface Itest { @GET("http://www.baidu.com/") Call<ResponseBody> get(); }compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'