1.www.github.com下载jar包
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <EditText android:id="@+id/et_username" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="请输入用户名" /> <EditText android:id="@+id/et_password" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="请输入密码" /> <Button android:onClick="click1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="asyClient get请求" /> <Button android:onClick="click2" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="asyClient post请求" /> </LinearLayout>
2.MyAcitivity
package com.example.aysncHttp; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.Toast; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import com.loopj.android.http.RequestParams; public class MyActivity extends Activity { private EditText et_username; private EditText et_password; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); et_username = (EditText)findViewById(R.id.et_username); et_password = (EditText)findViewById(R.id.et_password); } public void click1(View v) { String username = et_username.getText().toString().trim(); String password = et_password.getText().toString().trim(); AsyncHttpClient asyncHttpClient = new AsyncHttpClient(); String url = "http://172.16.1.1:91/api/test/?djxm="+username+"&password="+password; asyncHttpClient.get(url,new AsyncHttpResponseHandler (){ @Override public void onFailure(Throwable error) { super.onFailure(error); Toast.makeText(MyActivity.this,"请求失败",1).show(); } @Override public void onSuccess(String content) { super.onSuccess(content); Toast.makeText(MyActivity.this,content,1).show(); } }); } public void click2(View v) { String username = et_username.getText().toString().trim(); String password = et_password.getText().toString().trim(); AsyncHttpClient asyncHttpClient = new AsyncHttpClient(); String url = "http://172.16.1.1:91/api/test/"; RequestParams params = new RequestParams(); params.put("djxm",username); params.put("password",password); asyncHttpClient.post(url,params,new AsyncHttpResponseHandler (){ @Override public void onFailure(Throwable error) { super.onFailure(error); Toast.makeText(MyActivity.this,"请求失败",1).show(); } @Override public void onSuccess(String content) { super.onSuccess(content); Toast.makeText(MyActivity.this,content,1).show(); } }); } }
3.清单文件中配置权限
<uses-permission android:name="android.permission.INTERNET"/>