使用开源框架进行get,post提交
package com.example.aysnhttp; import java.net.URLEncoder; import org.apache.http.Header; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import com.loopj.android.http.RequestParams; import android.os.Bundle; import android.app.Activity; import android.view.View; import android.view.View.OnClickListener; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends Activity { private EditText ed1; private EditText ed2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ed1 = (EditText) findViewById(R.id.et1); ed2 = (EditText) findViewById(R.id.et2); findViewById(R.id.btn_get).setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub String name = ed1.getText().toString(); String pass = ed2.getText().toString(); String path = "http://192.168.21.1:8080/ok/servlet/Login?username=" + URLEncoder.encode(name) + "&password=" + pass; AsyncHttpClient client = new AsyncHttpClient(); client.get(path, new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { // TODO Auto-generated method stub String msg = new String(responseBody); Toast.makeText(MainActivity.this, msg, 0).show(); } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { // TODO Auto-generated method stub } }); } }); findViewById(R.id.btn_post).setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub String name = ed1.getText().toString(); String pass = ed2.getText().toString(); String path = "http://192.168.21.1:8080/ok/servlet/Login"; AsyncHttpClient client = new AsyncHttpClient(); RequestParams params = new RequestParams(); params.add("username", URLEncoder.encode(name)); params.add("password", pass); client.post(path, params, new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { // TODO Auto-generated method stub String msg = new String(responseBody); Toast.makeText(MainActivity.this, msg, 0).show(); } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { // TODO Auto-generated method stub } }); } }); } }