欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

怎样实现android http-post方法实例说明

程序员文章站 2023-01-02 08:35:22
复制代码 代码如下: package com.hl; import java.io.bufferedreader; import java.io.ioexception;...
复制代码 代码如下:

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();
}
}