android开发中网络通讯必不可少,目前使用率较高的http框架有Okhttp、nohttp、volley等等,
下面做一个用户登陆的demo,说明一下Okhttp的用法,废话不多说,看代码。
LoginActivity.java
1 package com.junyi.shangqifixture; 2 3 import java.io.IOException; 4 5 import android.app.Activity; 6 import android.content.Intent; 7 import android.os.AsyncTask; 8 import android.os.Bundle; 9 import android.view.View;10 import android.view.View.OnClickListener;11 import android.widget.Button;12 import android.widget.EditText;13 import okhttp3.FormBody;14 import okhttp3.OkHttpClient;15 import okhttp3.Request;16 import okhttp3.RequestBody;17 import okhttp3.Response;18 19 public class LoginActivity extends Activity {20 21 private final OkHttpClient client = new OkHttpClient();22 private EditText editAccount,editPwd;23 24 @Override25 protected void onCreate(Bundle savedInstanceState) {26 // TODO Auto-generated method stub27 super.onCreate(savedInstanceState);28 setContentView(R.layout.activity_login);29 30 editAccount=(EditText)findViewById(R.id.accountEdittext);31 editPwd=(EditText)findViewById(R.id.pwdEdittext);32 33 Button btnLogin=(Button)findViewById(R.id.login_in);34 btnLogin.setOnClickListener(new OnClickListener() {35 36 @Override37 public void onClick(View arg0) {38 // TODO Auto-generated method stub39 new AnsyTry().execute(editAccount.getText().toString(),editPwd.getText().toString());40 }41 });42 }43 44 private class AnsyTry extends AsyncTask{45 46 @Override47 protected String doInBackground(String... params) {48 // TODO Auto-generated method stub49 try {50 RequestBody formBody = new FormBody.Builder()51 .add("account", params[0])52 .add("pwd", params[1])53 .build();54 55 Request request = new Request.Builder()56 .url("http://baidu.com")57 .post(formBody)58 .build();59 60 Response response = client.newCall(request).execute();61 if(response.isSuccessful()){62 return response.body().string();63 }64 } catch (IOException e) {65 // TODO Auto-generated catch block66 e.printStackTrace();67 }68 return null;69 }70 71 @Override72 protected void onPostExecute(String result) {73 // TODO Auto-generated method stub74 super.onPostExecute(result);75 76 //TODO 此处判断返回值77 78 Intent intent = new Intent();79 intent.setClass(LoginActivity.this, MainActivity.class);80 startActivity(intent);81 finish();82 }83 }84 }
activity_login.xml
1 27 8 15 16 21 22 85 86 91 9230 31 52 5339 40 51 61 62 8470 71 83 100 101
2016-05-31 14:52:30