使用HttpClient进行Post方式通信,通过HttpClient建立网络链接,使用HttpPost方法传出数据与读取数据,传出和传入的数据都是Entity的子类。
package com.example.httpclientpost;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import com.example.httpclientget.R;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private EditText et;
private TextView text;
HttpClient client;//通过HttpClient建立网络链接
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
client = new DefaultHttpClient();//创建一个默认的client对象
et = (EditText) findViewById(R.id.edtext);
text = (TextView) findViewById(R.id.textView);
findViewById(R.id.button).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
readNet("http://10.0.2.2:8080/MyWebTest/Do" ,et.getText().toString());
}
});
}
public void readNet(String url,String in){ //比get多添加一个参数
new AsyncTask<String, Void, String>() {
@Override
protected String doInBackground(String... params) {
String urlString = params[0];
HttpPost post = new HttpPost(urlString);//HttpPost对象
/*
* 因为服务器获取的是表单格式,所以get方式的String格式便不可用,要将它改为表单格式
*/
try {
List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
list.add(new BasicNameValuePair("name", params[1]));
post.setEntity(new UrlEncodedFormEntity(list)); //post方法传出数据,类似getEntity(),把list转换为entity格式
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
HttpResponse response = client.execute(post); //execute返回一个 HttpResponse对象
String valString = EntityUtils.toString(response.getEntity());// 通过Response获取Entity返回值。
System.out.println(valString);
return valString;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/*
* 实现返回editText中的内容,重写onPostExecute方法
*/
@Override
protected void onPostExecute(String result) {
text.setText(result);
}
}.execute(url,in);
}
}