关于HttpClientPost的具体用法

来源:互联网 发布:centos nginx php 编辑:程序博客网 时间:2024/05/21 10:09




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 postLogin(View v) {
String username = et_username.getText().toString().trim();
String password = et_password.getText().toString().trim();
String path = "http://192.168.1.102:8080/LoginTest/servlet/LoginServlet";
post_login(path, username, password);
}


private void post_login(final String path, final String username,
final String password) {
new Thread() {
public void run() {
try {
// 创建HttpClient对象
HttpClient httpClient = new DefaultHttpClient();
// 创建HttpPost对象
HttpPost httpPost = new HttpPost(path);
// 创建一个泛型为键值对类型的集合
List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
// 添加参数信息
parameters
.add(new BasicNameValuePair("username", username));
parameters
.add(new BasicNameValuePair("password", password));
// 创建出实体内容对象
HttpEntity entity = new UrlEncodedFormEntity(parameters,
"utf-8");
// 设置请求的实体内容
httpPost.setEntity(entity);
// 执行post请求
HttpResponse httpResponse = httpClient.execute(httpPost);
// 获取响应码
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);
}


}

0 1