public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final int GET = 1;
private Button btn_okhttp;
private TextView tv_okhttp;
private OkHttpClient client = new OkHttpClient();
//private String abc;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case GET:
tv_okhttp.setText((String) msg.obj);
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_okhttp = (Button) findViewById(R.id.btn_okhttp);
tv_okhttp = (TextView) findViewById(R.id.tv_okhttp);
btn_okhttp.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_okhttp:
getDataFromGet();
break;
}
}
private void getDataFromGet() {
new Thread() {
@Override
public void run() {
super.run();
try {
String result = get("https://gank.io/api/today");
JSONObject jsonObject = new JSONObject(result);
JSONObject results = jsonObject.getJSONObject("results");
String android= results.getString("Android");
Log.e("ZHUTI",android);
Message msg = Message.obtain();
msg.what = GET;
msg.obj = android;
handler.sendMessage(msg);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}.start();
}
private String get(String url) throws IOException {
Request request = new Request.Builder().url(url).build();
Response response = client.newCall(request).execute();
return response.body().string();
}
}
<uses-permission android:name="android.permission.INTERNET"/>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<Button
android:id="@+id/btn_okhttp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button" />
<TextView
android:id="@+id/tv_okhttp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btn_okhttp" />
</LinearLayout>