本文實(shí)例為大家分享了使用OkHttp發(fā)送post請(qǐng)求的具體代碼,供大家參考,具體內(nèi)容如下
成都創(chuàng)新互聯(lián)主要從事成都網(wǎng)站制作、做網(wǎng)站、網(wǎng)頁設(shè)計(jì)、企業(yè)做網(wǎng)站、公司建網(wǎng)站等業(yè)務(wù)。立足成都服務(wù)亳州,十載網(wǎng)站建設(shè)經(jīng)驗(yàn),價(jià)格優(yōu)惠、服務(wù)專業(yè),歡迎來電咨詢建站服務(wù):18980820575
MainActivity.java
public class MainActivity extends AppCompatActivity { private EditText mEt_qq; private EditText mEt_pwd; private TextView mTv_status; String path = "http://169.254.53.96:8080/web/LoginServlet"; private static final int SUCCESS = 665; private static final int FALL = 894; Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what) { case SUCCESS: String text= (String) msg.obj; mTv_status.setText(text); break; case FALL: Toast.makeText(MainActivity.this, "沒有網(wǎng)", Toast.LENGTH_SHORT).show(); break; default: break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //對(duì)控件進(jìn)行初始化操作 initVIew(); } private void initVIew() { mEt_qq = (EditText) findViewById(R.id.et_qq); mEt_pwd = (EditText) findViewById(R.id.et_pwd); mTv_status = (TextView) findViewById(R.id.tv_status); } /** * 使用Post進(jìn)行表單(鍵值對(duì))上傳,完成登錄 * @param view */ public void login(View view){ //得到用戶輸入的信息,進(jìn)行非空判斷 String qq = mEt_qq.getText().toString().trim(); String pwd =mEt_pwd.getText().toString().trim(); if(TextUtils.isEmpty(qq) || TextUtils.isEmpty(pwd) ){ Toast.makeText(MainActivity.this, "不能輸入為空", Toast.LENGTH_SHORT).show(); return; } //1.0 創(chuàng)建okhttpClinet OkHttpClient okHttpClient = new OkHttpClient.Builder() .connectTimeout(10, TimeUnit.SECONDS) .readTimeout(10,TimeUnit.SECONDS) .writeTimeout(10,TimeUnit.SECONDS) .build(); FormBody formBody= new FormBody.Builder() .add("qq", qq).add("pwd", pwd) .build(); Request request= new Request.Builder() .post(formBody) .url(path) .build(); Call call = okHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { handler.sendEmptyMessage(FALL); } @Override public void onResponse(Call call, Response response) throws IOException { String string = response.body().string(); Message msg = Message.obtain(); msg.obj=string; msg.what=SUCCESS; handler.sendMessage(msg); } }); } }
activity_main.xml
build.gradle //依賴
implementation 'com.squareup.okhttp3:okhttp:3.4.2'
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。