核心代码:
import java.io.IOException;
import org.apache.http.Header;
import android.content.Context;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
public class LoginService {
/**
* 1、使用AsyncHttpClient——GET方式进行登录
*
* @throws IOException
*/
public static void loginByGet(final Context context, String username,
String password)
throws IOException {
System.out.println("以Async GET方式提交。。。");
String path = "http://192.168.221.221:8080/web/LoginServlet?username="+ username + "&password=" + password;
AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
asyncHttpClient.get(path, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, String content) {
System.out.println("statusCode为:" + statusCode);
Toast.makeText(context, content, 0).show();
}
@Override
protected void sendFailureMessage(int statusCode, Header[] headers,
Throwable e, String responseBody) {
Toast.makeText(context, "GET请求失败", 0).show();
}
});
}
/**
* 2、使用AsyncHttpClient——POST方式登录
*
* @param username
* @param password
* @return
* @throws IOException
*/
public static void loginByPost(final Context context, String username,
String password)
throws IOException {
System.out.println("以Async POST方式登录。。。");
String path = "http://192.168.221.221:8080/web/LoginServlet";
AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("username", username);
params.put("password", password);
asyncHttpClient.post(path, params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String content) {
Toast.makeText(context, content, 0).show();
}
@Override
protected void sendFailureMessage(int statusCode, Header[] headers,
Throwable e, String responseBody) {
Toast.makeText(context, "POST请求失败", 0).show();
}
});
}
}
|