在API 22中发布到PHP脚本

时间:2015-10-27 14:21:58

标签: php android http http-post

在API 22中,一切似乎都被弃用了。我可以在API 22下面发布到服务器,但是如何在API 22之上完成?我找不到任何东西,因为它仍然太新了。 以下是我在API 22下工作的内容

public static void sendData(final String name,  final String from, final String message)
{


    Thread thread = new Thread(new Runnable(){
            @Override
            public void run(){
                String content = "";
                //code to do the HTTP request
                try
                {               
                    /* Sends data through a HTTP POST request */
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost("http://mywebsite.com/contact.php");
                    List <NameValuePair> params = new ArrayList <NameValuePair>();
                    params.add(new BasicNameValuePair("cf_name", name));

                    params.add(new BasicNameValuePair("cf_email", from));

                    params.add(new BasicNameValuePair("cf_message", message));
                    httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));

                    /* Reads the server response */
                    HttpResponse response = httpClient.execute(httpPost);
                    InputStream in = response.getEntity().getContent();

                    StringBuffer sb = new StringBuffer();
                    int chr;
                    while ((chr = in.read()) != -1)
                    {
                        sb.append((char) chr);
                    }
                    content = sb.toString();
                    in.close();

                    /* If there is a response, display it */
                    if (!content.equals(""))
                    {
                        Log.i("HTTP Response", content);
                    }
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        });
    thread.start();


}

1 个答案:

答案 0 :(得分:0)

最后我尝试了很多解决方案,唯一有效的解决方案是来自Fahim的answer