发送get请求
创建一个客户端对象
HttpClient client = new DefaultHttpClient();
创建一个get请求对象
HttpGet hg = new HttpGet(path);
发送get请求,建立连接,返回响应头对象
HttpResponse hr = hc.execute(hg);
获取状态行对象,获取状态码,如果为200则说明请求成功
if(hr.getStatusLine().getStatusCode() == 200){ //拿到服务器返回的输入流 InputStream is = hr.getEntity().getContent(); String text = Utils.getTextFromStream(is); }
代码
public void get(View v){
EditText et_name = (EditText) findViewById(R.id.et_name);
EditText et_pass = (EditText) findViewById(R.id.et_pass);
final String name = et_name.getText().toString();
final String pass = et_pass.getText().toString();
Thread t = new Thread(){
@Override
public void run() {
String path = "http://192.168.1.130/Web/servlet/CheckLogin?name=" +
URLEncoder.encode(name) + "&pass=" + pass;
//使用httpClient框架做get方式提交
//1.创建HttpClient对象
HttpClient hc = new DefaultHttpClient();
//2.创建httpGet对象,构造方法的参数就是网址
HttpGet hg = new HttpGet(path);
//3.使用客户端对象,把get请求对象发送出去
try {
HttpResponse hr = hc.execute(hg);
//拿到响应头中的状态行
StatusLine sl = hr.getStatusLine();
if(sl.getStatusCode() == 200){
//拿到响应头的实体
HttpEntity he = hr.getEntity();
//拿到实体中的内容,其实就是服务器返回的输入流
InputStream is = he.getContent();
String text = Utils.getTextFromStream(is);
//发送消息,让主线程刷新ui显示text
Message msg = handler.obtainMessage();
msg.obj = text;
handler.sendMessage(msg);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
t.start();
}
public class Utils {
public static String getTextFromStream(InputStream is){
byte[] b = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
while((len = is.read(b)) != -1){
bos.write(b, 0, len);
}
String text = new String(bos.toByteArray());
bos.close();
return text;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}