Android HttpPost。将数据发送到PHP服务器上的表单

时间:2013-03-07 16:02:02

标签: android http-post

我正在使用最新的Java Eclipse软件,并且在运行此HttpPost代码时模拟器崩溃了。我在笔记本电脑上安装了uniserver,因此我将其用作服务器。

此代码应该调用前一个类的编辑文本数据,并使用HttpPost请求将此数据发布到在线表单的各自字段中。

编辑文本数据有3个字段:“From”,“To”和“Message”。我在服务器上创建的表单也有相同的字段来输入数据。 (“http://19x.xx.xx.xxx/androidp2p/testform.php”)其中19x.xx.xx.xxx是我的(本地主机)IP地址。

我正在从前一个类中正确地提取数据,我的代码类似于我在网上找到的HttpPost示例,但我不确定它为什么会崩溃。

我附上了HttpPost方法,我试着看看能不能得到任何帮助。提前感谢你。

方法1:

String myBreadu, myBreadr, myBreadm;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    Bundle myBasket = getIntent().getExtras();
    myBreadu = myBasket.getString("keyfrom");
    myBreadr = myBasket.getString("keyto");
    myBreadm = myBasket.getString("keymsg");
    // Create a new HttpClient and Post Header
    HttpClient client = new DefaultHttpClient();
    String postURL = ("http://19x.xx.xx.xxx/androidp2p/testform.php");
    HttpPost post = new HttpPost(postURL);
    try {
        // Add the data
        List<NameValuePair> pairs = new ArrayList<NameValuePair>(3);
        pairs.add(new BasicNameValuePair("keysendu", myBreadu));
        pairs.add(new BasicNameValuePair("keysendr", myBreadr));
        pairs.add(new BasicNameValuePair("keysendm", myBreadm));
        UrlEncodedFormEntity uefe = new UrlEncodedFormEntity(pairs);
        post.setEntity(uefe);
        // Execute the HTTP Post Request
        HttpResponse response = client.execute(post);
        // Convert the response into a String
        HttpEntity resEntity = response.getEntity();
        if (resEntity != null) {
            Log.i("RESPONSE", EntityUtils.toString(resEntity));
        }
    } catch (UnsupportedEncodingException uee) {
        uee.printStackTrace();
    } catch (ClientProtocolException cpe) {
        cpe.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }

}

方法2:

String myBreadu, myBreadr, myBreadm;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    Bundle myBasket = getIntent().getExtras();
    myBreadu = myBasket.getString("keyfrom");
    myBreadr = myBasket.getString("keyto");
    myBreadm = myBasket.getString("keymsg");
    String result = null;
    // Create a new HttpClient and Post Header
    HttpClient client = new DefaultHttpClient();
    String postURL = ("http://186.45.107.129/androidp2p/testform.php");
    HttpPost post = new HttpPost(postURL);
    try {
        // Add the data
        List<NameValuePair> pairs = new ArrayList<NameValuePair>(3);
        pairs.add(new BasicNameValuePair("keysendu", myBreadu));
        pairs.add(new BasicNameValuePair("keysendr", myBreadr));
        pairs.add(new BasicNameValuePair("keysendm", myBreadm));
        UrlEncodedFormEntity uefe = new UrlEncodedFormEntity(pairs);
        post.setEntity(uefe);
        // Execute the HTTP Post Request
        HttpResponse response = client.execute(post);
        // Convert the response into a String
        HttpEntity resEntity = response.getEntity();
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String l = "";
        StringBuilder sb = new StringBuilder();
        while ((l = rd.readLine()) != null) {
            sb.append(l + "\n");
        }
        rd.close();
        String result = sb.toString(); // this line gives an error "Duplicate local variable result"
    } catch (UnsupportedEncodingException uee) {
        uee.printStackTrace();
    } catch (ClientProtocolException cpe) {
        cpe.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }

}

这是testform.PHP

测试表格

来源:
要:
消息:

我可以再添加一件吗?我不确定是否应该将数据直接发送到表单或我拥有的其他PHP页面。

顺便说一下,当我尝试HttpPost时,我在日志中遇到的错误是:

FATAL EXCEPTION: main

03-07 11:36:23.226: E/AndroidRuntime(1490): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.project.keegan/com.project.keegan.SendPostMethod}: android.os.NetworkOnMainThreadException

03-07 11:36:23.226: E/AndroidRuntime(1490):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)

03-07 11:36:23.226: E/AndroidRuntime(1490):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)

03-07 11:36:23.226: E/AndroidRuntime(1490):     at android.app.ActivityThread.access$600(ActivityThread.java:130)

对不起,如果这是太多的信息家伙。感谢。

1 个答案:

答案 0 :(得分:1)

您需要使用AsyncTask来执行所有网络操作。

您的网络操作可能会花费大量时间,如果在主UI线程上完成,UI将无法响应。如果您的用户界面长时间冻结,应用程序可能会被操作系统杀死。

因此,Android 4+强制要求使用后台线程来执行网络操作。

使用 doInBacground() 将代码放在 execute() 和所有AsyncTask中进行网络活动。

以下是您的AsyncTask的样子:

private class SendData extends AsyncTask<String, Integer, Void> {
     protected void doInBackground() {
// Create a new HttpClient and Post Header
HttpClient client = new DefaultHttpClient();
String postURL = ("http://19x.xx.xx.xxx/androidp2p/testform.php");
HttpPost post = new HttpPost(postURL);
try {
    // Add the data
    List<NameValuePair> pairs = new ArrayList<NameValuePair>(3);
    pairs.add(new BasicNameValuePair("keysendu", myBreadu));
    pairs.add(new BasicNameValuePair("keysendr", myBreadr));
    pairs.add(new BasicNameValuePair("keysendm", myBreadm));
    UrlEncodedFormEntity uefe = new UrlEncodedFormEntity(pairs);
    post.setEntity(uefe);
    // Execute the HTTP Post Request
    HttpResponse response = client.execute(post);
    // Convert the response into a String
    HttpEntity resEntity = response.getEntity();
    if (resEntity != null) {
        Log.i("RESPONSE", EntityUtils.toString(resEntity));
    }
} catch (UnsupportedEncodingException uee) {
    uee.printStackTrace();
} catch (ClientProtocolException cpe) {
    cpe.printStackTrace();
} catch (IOException ioe) {
    ioe.printStackTrace();
}
        
 }

 protected void onProgressUpdate() {
    //called when the background task makes any progress
 }

  protected void onPreExecute() {
     //called before doInBackground() is started
 }
 protected void onPostExecute() {
     //called after doInBackground() has finished 
 }
  }

您可以使用 new SendData().execute("");

在任何地方拨打电话