package com.hl;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.inputStream;
import java.io.inputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.apache.http.httpentity;
import org.apache.http.httpResponse;
import org.apache.http.clIEnt.entity.UrlEncodedFormEntity;
import org.apache.http.clIEnt.methods.httpPost;
import org.apache.http.impl.clIEnt.DefaulthttpClIEnt;
import org.apache.http.message.BasicnameValuePair;
import androID.app.Activity;
import androID.os.Bundle;
import androID.vIEw.VIEw;
import androID.vIEw.VIEw.OnClickListener;
import androID.Widget.button;
import androID.Widget.EditText;
import androID.Widget.TextVIEw;
public class SimplePOST extends Activity {
private TextVIEw show;
private EditText txt;
private button btn;
@OverrIDe
public voID onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentVIEw(R.layout.main);
show = (TextVIEw)findVIEwByID(R.ID.show);
txt = (EditText)findVIEwByID(R.ID.txt);
btn = (button)findVIEwByID(R.ID.btn);
btn.setonClickListener(new OnClickListener() {
@OverrIDe
public voID onClick(VIEw v) {
dopost(txt.getText().toString());
}
});
}
private voID dopost(String val){
//封装数据
Map<String,String> parmas = new HashMap<String,String>();
parmas.put("name",val);
DefaulthttpClIEnt clIEnt = new DefaulthttpClIEnt();//http客户端
httpPost httpPost = new httpPost("http://mhycoe.com/test/post.PHP");
ArrayList<BasicnameValuePair> pairs = new ArrayList<BasicnameValuePair>();
if(parmas != null){
Set<String> keys = parmas.keySet();
for(Iterator<String> i = keys.iterator(); i.hasNext();) {
String key = (String)i.next();
pairs.add(new BasicnameValuePair(key,parmas.get(key)));
}
}
try {
UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(pairs,"utf-8");
/*
* 将POST数据放入http请求
*/
httpPost.setEntity(p_entity);
/*
* 发出实际的http POST请求
*/
httpResponse response = clIEnt.execute(httpPost);
httpentity entity = response.getEntity();
inputStream content = entity.getContent();
String returnConnection = convertStreamToString(content);
show.setText(returnConnection);
} catch (IllegalStateException e) {
e.printstacktrace();
} catch (IOException e) {
e.printstacktrace();
}
}
private String convertStreamToString(inputStream is) {
BufferedReader reader = new BufferedReader(new inputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readline()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printstacktrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printstacktrace();
}
}
return sb.toString();
}
}
总结
以上是内存溢出为你收集整理的怎样实现android http-post方法实例说明全部内容,希望文章能够帮你解决怎样实现android http-post方法实例说明所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)