HttpUrlConnection和HttpClient和android-async-http框架的GET和POST请求

时间:2022-11-26 14:31:23

1.HttpUrlConnection

public class NetUtil {
public static String doGet(String username,String password) {
try {
String data = "username=" + username + "&password=" + password;
URL url = new URL("http://115.192.188.146:9090/Android//servlet/LoginServlet?"+data);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(3000);
conn.setReadTimeout(5000);

if(conn.getResponseCode()==200){
InputStream is = conn.getInputStream();
String result = getStringFromInputStream(is);
return result;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

public static String doPost(String username,String password) {
try {
// post请求的参数
String data = "username=" + username + "&password=" + password;
URL url = new URL("http://115.192.188.146:9090/Android//servlet/LoginServlet");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(3000);
conn.setReadTimeout(5000);
conn.setDoOutput(true);//默认情况下, 系统不允许向服务器输出内容

// 获得一个输出流, 用于向服务器写数据, 默认情况下, 系统不允许向服务器输出内容 所以要设置conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
os.write(data.getBytes());//将请求的数据写入输出流里
os.flush();
os.close();

if(conn.getResponseCode()==200){
InputStream is = conn.getInputStream();
String result = getStringFromInputStream(is);
return result;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

private static String getStringFromInputStream(InputStream is) {
try {
if(is!=null){
int len = 0;
byte[] buffer = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while((len=is.read(buffer))!=-1){
baos.write(buffer, 0, len);
}
String result = baos.toString();
is.close();
baos.close();
return result;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}


2.HttpClient

public class NetUtil {
public static String doHttpClientGet(String username,String password) {
HttpClient client = null;
try {
String data = "username=" + username + "&password=" + password;

client = new DefaultHttpClient();
HttpGet get = new HttpGet("http://10.0.2.2:9090/Android//servlet/LoginServlet?"+data);

HttpResponse response = client.execute(get);
if(response.getStatusLine().getStatusCode()==200){
InputStream is = response.getEntity().getContent();
return getStringFromInputStream(is);
}

} catch (Exception e) {
e.printStackTrace();
} finally {
if(client!=null){//关闭连接
client.getConnectionManager().shutdown();
}
}
return null;
}

public static String doHttpClientPost(String username,String password) {
HttpClient client = null;
try {
client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://10.0.2.2:9090/Android//servlet/LoginServlet");
//设置请求的参数
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("username", username));
parameters.add(new BasicNameValuePair("password", password));
//把post请求的参数包装了一层
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters);
//设置参数
post.setEntity(entity);

HttpResponse response = client.execute(post);
if(response.getStatusLine().getStatusCode()==200){
InputStream is = response.getEntity().getContent();
return getStringFromInputStream(is);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if(client!=null){
client.getConnectionManager().shutdown();
}
}
return null;
}

private static String getStringFromInputStream(InputStream is) {
try {
if(is!=null){
int len = 0;
byte[] buffer = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while((len=is.read(buffer))!=-1){
baos.write(buffer, 0, len);
}
String result = baos.toString();
is.close();
baos.close();
return result;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}

3.android-async-http  

public class MainActivity extends Activity {

private EditText et_username;
private EditText et_password;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}

private void init() {
et_username = (EditText) findViewById(R.id.et_username);
et_password = (EditText) findViewById(R.id.et_password);
}

public void loginGET(View view){
String username = et_username.getText().toString();
String password = et_password.getText().toString();

String data = "username=" + username + "&password=" + password;
String url = "http://10.0.2.2:9090/Android//servlet/LoginServlet?"+data;
AsyncHttpClient client = new AsyncHttpClient();
client.get(url, new MyResponseHandler());//get请求
}

public void loginPOST(View view){
String username = et_username.getText().toString();
String password = et_password.getText().toString();

String url = "http://10.0.2.2:9090/Android//servlet/LoginServlet";
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("username", username);
params.put("password", password);
client.post(url, params , new MyResponseHandler());//post请求
}

private class MyResponseHandler extends AsyncHttpResponseHandler{
//请求成功时调用
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
//这个回调方法是在主线程执行的,所以在这个方法里可以直接操作UI组件
Toast.makeText(getApplicationContext(), "成功:"+statusCode+" body--->"+new String(responseBody), Toast.LENGTH_SHORT).show();
}
//请求失败时调用
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Toast.makeText(getApplicationContext(), "失败:"+statusCode, Toast.LENGTH_SHORT).show();
}
}
}