使用android studio。
1、加入联网权限
<uses-permission android:name="android.permission.INTERNET" />
2、UI设计
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="测试okhttp"
android:id="@+id/testButton"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="@+id/testTextView"/>
3、build.gradle中添加依赖
compile 'com.squareup.okhttp3:okhttp:3.4.2'
4、Java代码
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private Button mTestButton;
private TextView mTestTextView;
private String LOG_TAG = "log_main";
private Handler mHandler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTestButton = (Button) findViewById(R.id.testButton);
mTestTextView = (TextView) findViewById(R.id.testTextView);
Log.v(LOG_TAG, "测试测试测试测试");
mTestButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.v(LOG_TAG, "按钮点击");
Toast.makeText(MainActivity.this, "测试", Toast.LENGTH_LONG).show();
makeHttpRequest();
}
});
}
private void makeHttpRequest() {
okhttp3.OkHttpClient mOkHttpClient = new okhttp3.OkHttpClient();
final okhttp3.Request request = new okhttp3.Request.Builder()
.url("https://www.baidu.com")
.build();
okhttp3.Call call = mOkHttpClient.newCall(request);
call.enqueue(new okhttp3.Callback()
{
@Override
public void onFailure(okhttp3.Call call, IOException e) {
}
@Override
public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
final String htmlStr = response.body().string();
mHandler.post(new Runnable() {
@Override
public void run() {
mTestTextView.setText("返回数据: " + htmlStr);
// Toast不能放在这里
}
});
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(MainActivity.this, "数据长度:"+htmlStr.length(), Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
效果: