Android 通过HTTPCLINET POST请求互联网数据

时间:2022-09-23 20:50:04
private EditText et;
private TextView tv;
HttpClient client; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et=(EditText) findViewById(R.id.et);
tv=(TextView) findViewById(R.id.tv);
client=new DefaultHttpClient();
findViewById(R.id.btn).setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
readNet("http://localhost:8080/get",et.getText()+""); }
});
} public void readNet(String url,String name){
new AsyncTask<String, Void, String>() { @Override
protected String doInBackground(String... params) {
String urlString=params[0];
HttpPost post=new HttpPost(urlString);
try {
HttpResponse response=client.execute(post);
List<BasicNameValuePair> list=new ArrayList<BasicNameValuePair>();
list.add(new BasicNameValuePair("name", params[1]));
post.setEntity(new UrlEncodedFormEntity(list));
String v=EntityUtils.toString( response.getEntity());
return v;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
} @Override
protected void onPostExecute(String result) {
tv.setText(result);
} }.execute(url,name);
}

(ˉ(∞)ˉ) :由于是使用表单的方式提交数据,所以应该用

 List<BasicNameValuePair> list=new ArrayList<BasicNameValuePair>();
键值对的方式。