博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Android处理POST请求、Android用SAX解析XML
阅读量:4172 次
发布时间:2019-05-26

本文共 5194 字,大约阅读时间需要 17 分钟。

1、处理post请求
public class HttpGet extends Activity {
private boolean isAuthenticated;
private ArrayList<BasicNameValuePair> pairs;
private DefaultHttpClient httpclient;
private HttpPost httppost;
private InputStream content;
private String returnConnection;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv=new TextView(this);
Map vars=new HashMap();
vars.put("mydata", "Hello,Android");
ParameterHttp("http://5billion.com.cn/post.php",vars);
doPost();
tv.setText(this.returnConnection);
this.setContentView(tv);
}
private void ParameterHttp(String url, Map vars) {
this.httpclient=new DefaultHttpClient();
this.httppost=new HttpPost(url);
this.pairs=new ArrayList();
if(vars!=null){
Set keys=vars.keySet();
for(Iterator i=keys.iterator();i.hasNext();){
String key=(String)i.next();
pairs.add(new BasicNameValuePair(key,(String) vars.get(key)));
}
}
}
private String doPost() {
try{
UrlEncodedFormEntity p_entity=new UrlEncodedFormEntity(pairs,"ISO-8859-1");
httppost.setEntity(p_entity);
HttpResponse response=httpclient.execute(httppost);
HttpEntity entity=response.getEntity();
content=entity.getContent();
this.returnConnection=convertStreamToString(content);
Log.d("HttpPostConnection",">>>>>>>>>"+returnConnection);
int status_code=response.getStatusLine().getStatusCode();
if(status_code>=300){
this.isAuthenticated=false;
}else{
this.isAuthenticated=true;
}
}catch (Exception e) {
// TODO: handle exception
}
return returnConnection;
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
3、SAX解析xml
public class HttpGet extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv=new TextView(this);
try{
URL url=new URL("http://5billion.com.cn/example.xml");
//从SAXParserFactor获取SAXParser
SAXParserFactory spf=SAXParserFactory.newInstance();
SAXParser sp=spf.newSAXParser();
//从SAXParser获取XMLReader
XMLReader xr=sp.getXMLReader();
//创建文明自己的内容处理器
ExampleHandler myExampleHandler=new ExampleHandler();
//用内容处理器处理XMLReader
xr.setContentHandler(myExampleHandler);
//XMLReader获取xml文件
xr.parse(new InputSource(url.openStream()));
//用ExampleHandle解析XML中数据
ParsedExampleDataSet parsedExampleDataSet=myExampleHandler.getParsedData();
//将解析的结果显示到gui
tv.setText(parsedExampleDataSet.toString());
}catch (Exception e) {
tv.setText(e.getMessage());
}
this.setContentView(tv);
}
class ExampleHandler extends DefaultHandler {
private boolean in_outertag=false;
private boolean in_innertag=false;
private boolean in_mytag=false;
private ParsedExampleDataSet myParsedExampleDataSet=new ParsedExampleDataSet();
public ParsedExampleDataSet getParsedData(){
return this.myParsedExampleDataSet;
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if(this.in_mytag){
String str=new String(ch,start,length);
myParsedExampleDataSet.setExtractedString(str);
Log.v("ParsingXML","Characters():"+str);
}
}
@Override
public void startDocument() throws SAXException {
this.myParsedExampleDataSet=new ParsedExampleDataSet();
Log.v("ParsingXML","startDocument");
}
@Override
public void endDocument() throws SAXException {
Log.v("ParsingXML","endDocumnet");
}
@Override
public void startElement(String uri, String localName, String name,
Attributes attributes) throws SAXException {
if(localName.equals("outertag")){
this.in_outertag=true;
}else if(localName.equals("innertag")){
this.in_innertag=true;
}else if(localName.equals("mytag")){
this.in_mytag=true;
}else if(localName.equals("tagwithnumber")){
String attrValue=attributes.getValue("thenumber");
int i=Integer.parseInt(attrValue);
this.myParsedExampleDataSet.setExtractedInt(i);
}
Log.v("ParsingXML","StartElement():"+localName);
}
@Override
public void endElement(String uri, String localName, String name)
throws SAXException {
if(localName.equals("outertag")){
this.in_outertag=false;
}else if(localName.equals("innertag")){
this.in_innertag=false;
}else if(localName.equals("mytag")){
this.in_mytag=false;
}else if(localName.equals("tagwithnumber")){
//nothing to do
}
Log.v("ParsingXML","endElement():"+localName);
}
}
class ParsedExampleDataSet {
private String extractedString=null;
private int extractedInt=0;
public void setExtractedString(String extractedString) {
this.extractedString = extractedString;
}
public void setExtractedInt(int extractedInt) {
this.extractedInt = extractedInt;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "String from XML="+this.extractedString+"\n Number from XML="+this.extractedInt;
}
}
}

转载地址:http://ygbai.baihongyu.com/

你可能感兴趣的文章
Oracle外部表小例
查看>>
在VS.NET的VC++中运行控制台程序后暂停
查看>>
Linux下rz,sz与ssh,SecureCRT的配合使用
查看>>
一个使用Pro*C实现增删改查的小例子
查看>>
Save could not be completed. Eclipse国际化的问题解决
查看>>
Xblo(JSP+Servlet+JavaBean+Oracle单用户Blog)
查看>>
Unable to use IEC module under PortablePython_1.1_py2.5.4
查看>>
实用英文地址书写格式
查看>>
在oracle中通过connect by prior来实现递归查询!
查看>>
百度空间如何才能另存为 mht
查看>>
How to Reset or Change Microsoft Office 2007 Product License Key or Volume License Key (VLK)
查看>>
使用java concurrent调用xmlp api生成pdf
查看>>
Oracle日期计算之INTERVAL
查看>>
Oracle PL/SQL之EXCEPTION
查看>>
Oracle PL/SQL之EXCEPTION -- WHEN OTHERS THEN
查看>>
Oracle PL/SQL之VARCHAR2 QUALIFIER
查看>>
Oracle PL/SQL之处理index不连续的table类型变量
查看>>
Oracle PL/SQL之嵌套表(Nested Table)
查看>>
Oracle PL/SQL之令人不解的提示(nls_date_format)
查看>>
Oracle PL/SQL之GROUP BY ROLLUP
查看>>