用到的第三方包 OkHTTP
Github地址:https://github.com/square/okhttp
注意:
这里涉及到了网络操作,所以一定记得加上相关的权限:
- <uses-permission android:name="android.permission.INTERNET" />
一、GET请求:
- package barneyx.com.okhttpdemo;
- import android.support.v7.app.AppCompatActivity;
- import android.os.Bundle;
- import android.view.View;
- import android.widget.TextView;
- import org.w3c.dom.Text;
- import java.io.IOException;
- import okhttp3.Call;
- import okhttp3.Callback;
- import okhttp3.OkHttpClient;
- import okhttp3.Request;
- import okhttp3.Response;
- public class MainActivity extends AppCompatActivity {
- private String mBaseUrl = "http://192.168.0.17:8080/";
- private TextView tv;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- tv = (TextView)findViewById(R.id.t_view);
- }
- public void doGet(View view) throws IOException{
- //1.拿到okHttpClient对象
- OkHttpClient okHttpClient = new OkHttpClient();
- //2.构造Reqeust
- Request.Builder builder = new Request.Builder();
- Request request =builder.get().url(
- mBaseUrl+"user!login?username=bai&password=xiaobai"
- ).build();
- //3.将Request封装为Call
- Call call = okHttpClient.newCall(request);
- //Response response = call.execute();
- //4.执行Call
- call.enqueue(new Callback() {
- @Override
- public void onFailure(Call call, IOException e) {
- L.e("onFailure"+e.getMessage());
- e.printStackTrace();
- }
- @Override
- public void onResponse(Call call, Response response) throws IOException {
- L.e("OnResponse:");
- final String res = response.body().string();
- L.e(res);
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- tv.setText(res);
- }
- });
- }
- });
- }
- }
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:id="@+id/activity_main"
- android:orientation="vertical"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- tools:context="barneyx.com.okhttpdemo.MainActivity">
- <Button
- android:text="Get"
- android:onClick="doGet"
- android:layout_width="match_parent"
- android:layout_height="wrap_content" />
- <TextView
- android:id="@+id/t_view"
- android:text="hello world"
- android:gravity="center"
- android:paddingTop="10dp"
- android:layout_width="match_parent"
- android:layout_height="wrap_content" />
- </LinearLayout>