关于HttpClientGet的具体用法



public class MainActivity extends Activity {


protected static final int SUCCESS = 0;
protected static final int FAILED = 1;
private EditText et_username;
private EditText et_password;



Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {


case SUCCESS:
String content = (String) msg.obj;
Toast.makeText(MainActivity.this, content, 0).show();


break;
case FAILED:
Toast.makeText(MainActivity.this, "本次请求网路失败,请自行查找原因", 0).show();
break;
default:
break;
}
};
};


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_username = (EditText) findViewById(R.id.et_username);
et_password = (EditText) findViewById(R.id.et_password);
}


public void getLogin(View v) {
try {
String username = et_username.getText().toString().trim();
String password = et_password.getText().toString().trim();


// http://192.168.1.102:8080/LoginTest/servlet/LoginServlet?username=zhangsan&password=123


String path = "http://192.168.1.102:8080/LoginTest/servlet/LoginServlet?username="
+ URLEncoder.encode(username, "utf-8")
+ "&password="
+ URLEncoder.encode(password, "utf-8");


get_login(path);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}


}





private void get_login(final String path) {
new Thread() {
public void run() {
try {
// 创建http客户端对象
HttpClient httpClient = new DefaultHttpClient();
// 创建get请求对象 并设置网络路径
HttpGet httpGet = new HttpGet(path);
// 执行访问网络的操作
HttpResponse httpResponse = httpClient.execute(httpGet);
// 获取状态行,拿到状态码
int statusCode = httpResponse.getStatusLine()
.getStatusCode();
if (statusCode == 200) {
// 获取响应中的实体对象,然后获取实体内容
InputStream inputStream = httpResponse.getEntity()
.getContent();
String content = SteamToStr(inputStream);
// 将响应的实体内容发送给主线程
Message msg = Message.obtain();
msg.obj = content;
msg.what = SUCCESS;
handler.sendMessage(msg);


} else {
sendFailedMessage();
}


} catch (Exception e) {
e.printStackTrace();
sendFailedMessage();
}
}


}.start();
}


/**
* 将输入流转成字符串

* @param inputStream
* @return
* @throws IOException
*/

private String SteamToStr(InputStream inputStream) throws IOException {
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();


byte[] buffer = new byte[1024];
int len = 0;


while ((len = inputStream.read(buffer)) != -1) {
arrayOutputStream.write(buffer, 0, len);
}
String content = arrayOutputStream.toString();
return content;
};


/**
* 发送错误消息
*/

private void sendFailedMessage() {
Message msg = Message.obtain();
msg.what = FAILED;
handler.sendMessage(msg);
}


}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值