1

我正在使用最新的 java Eclipse 软件,当我运行这个 HttpPost 代码时模拟器崩溃了。我在笔记本电脑上安装了 uniserver,所以我将它用作服务器。

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

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

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

我附上了我试图查看是否可以获得任何帮助的 HttpPost 方法。提前谢谢你。

方法一:

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

}

方法二:

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)

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

4

1 回答 1

1

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

您的网络操作可能需要很长时间,如果在主 UI 线程上完成,UI 会变得无响应。如果您的 UI 长时间冻结,该应用程序可能会被操作系统杀死。

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

将代码放入内部进行网络活动doInBacground(),所有 AsyncTask 使用execute().

这是您的 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("");

于 2013-03-07T16:03:40.270 回答