如何使用Android通过Http post方法将数据发送到服务器?

时间:2012-03-14 14:16:18

标签: android jsp http-post

我正在尝试使用post方法将数据从Android手机发送到我的服务器

服务器:用JSP编写  数据库:JDO

http post,jsp文件和java代码的代码如图所示

   public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Button sig = (Button)findViewById(R.id.button1);
     sig.setOnClickListener(this);
    tv = (TextView)findViewById(R.id.textView1);
}

@Override
public void onClick(View arg0) {
    // TODO Auto-generated method stub
     HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://egencies.appspot.com");

        try {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
            nameValuePairs.add(new BasicNameValuePair("Rid", "00-22-68-E8-EC-F1"));
            nameValuePairs.add(new BasicNameValuePair("location", "bangalore"));
            nameValuePairs.add(new BasicNameValuePair("content", "hello frm android"));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            HttpResponse response = httpclient.execute(httppost);
            tv.setText(response.toString());

        } catch (ClientProtocolException e) {
        } catch (IOException e) {
        }

jsp文件表单标签:

<form action="/sign" method="get">
<div><input type="text" name="Rid" /></div>
<div><input type="text" name="location" /></div>
<div><textarea name="content" rows="3" cols="60"></textarea></div>
<div><input type="submit" value="Post Greeting" /></div>
<input type="hidden" name="guestbookName" value="<%= guestbookName %>"/>
</form>

JDO的java代码:

String guestbookName = req.getParameter("guestbookName");
Key guestbookKey = KeyFactory.createKey("Guestbook", guestbookName);
String content = req.getParameter("content");
String Rid = req.getParameter("Rid");
String location = req.getParameter("location");
Date date = new Date();
Entity greeting = new Entity("Greeting", guestbookKey);
greeting.setProperty("user", user);
greeting.setProperty("date", date);
greeting.setProperty("content", content);
greeting.setProperty("Rid", Rid);
greeting.setProperty("location", location);
DatastoreService datastore =
DatastoreServiceFactory.getDatastoreService();
datastore.put(greeting);

resp.sendRedirect("/guestbook.jsp?guestbookName="
             + guestbookName);"

当我发送它时,我收到msg说org.apache.http.message.BasicHttpResponse@44f94aa0 但没有任何东西存储在数据库中。 任何人都可以帮我这个吗?

1 个答案:

答案 0 :(得分:0)

表单本身是否正常?表单是使用GET,而不是POST,我想你的JDO的Java代码正在查看GET数据,而不是POST。因此,要么修改JDO的表单和java代码,要么使用POST,要么修改Android代码以使用GET。