今天要把Android上的某字串以XML的方式POST給Server,使用了JDOM(要先下載\並匯入.jar檔)將訊息建立成XML格式後存入字串變數,再以Post的方式給Server,如以下:
package com.fff;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
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 org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.output.XMLOutputter;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class JOM_POST_Test1Activity extends Activity {
/** Called when the activity is first created. */
String aa="";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
BuildXMLDoc();
} catch (Exception e) {
e.printStackTrace();
}
final String TAG = "ApacheHttpClientTest";
String response = "";
String url = "http://10.40.204.137:8080/project/test";
List params = new ArrayList();
params.add(new BasicNameValuePair("id",aa));
params.add(new BasicNameValuePair("name","kuka"));
try
{
response = httpPost(url, params);
} catch (Exception e)
{
e.printStackTrace();
}
Log.i(TAG, "####"+response);
}
public void BuildXMLDoc() throws IOException, JDOMException {
List list = new ArrayList();
List list2 = new ArrayList();
list.add(0, "1111111111"); list2.add(0, "11,22,33,44,55");
list.add(1, "2222222222"); list2.add(1, "11,22,33,44,55");
list.add(2, "3333333333"); list2.add(2, "11,22,33,44,55");
Element root = new Element("list");
Document Doc = new Document(root);
Element elements;
XMLOutputter outputter = new XMLOutputter();
for(小於list容量時)
{
elements= new Element("user");
elements.setAttribute("id", "" + i);
elements.addContent(new Element("_id").setText(list.get(i)));
elements.addContent(new Element("oj_want").setText(list2.get(i)));
root.addContent(elements);
aa+= outputter.outputString(elements);
}
System.out.println(aa);
/*
//如要產生XML的檔案使用以下
XMLOutputter XMLOut = new XMLOutputter();
XMLOut.output(Doc, new FileOutputStream("user.xml"));
*/
}
public String httpPost(String url, List params) throws Exception
{
String response = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try
{
httppost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
HttpResponse httpResponse = httpclient.execute(httppost);
int statusCode = httpResponse.getStatusLine().getStatusCode();
if(statusCode==HttpStatus.SC_OK)
{
response = EntityUtils.toString(httpResponse.getEntity());
}
else
{
response = "錯誤"+statusCode;
}
}catch (Exception e)
{
e.printStackTrace();
}
return response;
}
}