【问题标题】:Android, how to send POST requestAndroid,如何发送 POST 请求
【发布时间】:2013-02-26 06:16:43
【问题描述】:

我无法从我的 Android 应用程序向服务器发送发布请求。 我找到了一些关于如何发送 POST 的示例,但我的代码有一些错误,这里是代码:

public class MainActivity extends Activity 
{
private WebView wv; //Internet
private EditText email1; //Edit's
private EditText email2; //Edit's
private Button btn_get_access; //Get Access
private String post_url = "http://rasnacis.lv/vova.php";

@Override
public void onCreate(Bundle savedInstanceState)
{       
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    wv = (WebView) findViewById(R.id.webView1);
    email1 = (EditText) findViewById(R.id.txt_email_1);
    email2 = (EditText) findViewById(R.id.txt_email_2);
    btn_get_access = (Button) findViewById(R.id.btn_get_access);

    WebSettings webSettings = wv.getSettings();
    webSettings.setSaveFormData(true);

    //BUTTON
    OnClickListener ocl_btn_get_access = new OnClickListener()
    {

        public void onClick(View v) 
        {

            String givenEmail1 = email1.getEditableText().toString();
            String givenEmail2 = email2.getEditableText().toString();

            //SENDING POST
            if (givenEmail1.length() > 0 && givenEmail2.length() > 0)
            {
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(post_url);

                try
                {
                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                    nameValuePairs.add(new BasicNameValuePair("email1", "email2"));
                    nameValuePairs.add(new BasicNameValuePair("email1", "slgjlskjgsg"));
                    nameValuePairs.add(new BasicNameValuePair("email2", "xkjfhgkdjfhgkdjfg"));

                    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    httpClient.execute(httpPost);
                }
                catch (ClientProtocolException e) 
                {
                    System.out.println("First Exception caz of HttpResponese :" + e);
                    e.printStackTrace();
                }
                catch (IOException e) 
                {
                    System.out.println("Second Exception caz of HttpResponse :" + e);
                    e.printStackTrace();
                }
            }
            else
            {
                Toast.makeText(getBaseContext(), "All fields are required!", Toast.LENGTH_SHORT).show();
            }

            //sending GET
            //wv.loadUrl("http://rasnacis.lv/vova.php?email1=" + email1.getText() + "&email2=" + email2.getText());
        }
    };
    btn_get_access.setOnClickListener(ocl_btn_get_access);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

}

那么有人可以帮我吗?我刚开始Android开发,不知道很多技巧或困难的东西......

【问题讨论】:

  • 你检查过 吗?

标签: android post http-post


【解决方案1】:

我已经使用这种技术通过 post 方法敲击服务器:

new Thread( new Runnable() {
    @Override
    public void run() {
       try {
          query = "name="+username+"&pass="+passwaord;

          URL url = new URL("https:www.example.com/login.php");
          HttpURLConnection connection = (HttpURLConnection)url.openConnection();
          connection.setRequestProperty("Cookie", cookie);
          //Set to POST
          connection.setDoOutput(true);
          connection.setRequestMethod("POST");
          connection.setReadTimeout(10000);
          Writer writer = new OutputStreamWriter(connection.getOutputStream());
          writer.write(query);
          writer.flush();
          writer.close();
       } catch (Exception e) {
           // TODO Auto-generated catch block
           Log.e(Tag, e.toString());
       }
    }
}).start();

我希望它会有所帮助。请确保,cookie 是否需要为您的目的而发布。如果没有,那么你可以忽略connection.setRequestProperty("Cookie", cookie); 行。

query可以由BasicNameValuePair创建,但是我使用的过程对我来说更容易。

确保您已在清单中为互联网设置权限:

<uses-permission android:name="android.permission.INTERNET" />

【讨论】:

  • 我认为这是一个更好的答案,在可运行线程上进行 POST 将防止出现 NetworkOnMainThreadException。谢谢!
  • 此外,Apache 库已在 Android Marshmallow 中删除,因此这是现在唯一可行的选择。
  • 结果在哪里?
  • 如何得到post请求的响应?
  • @AsadullahAli:我已经很长时间没有在 android 上编码了。但是,我想你可以得到connection.getInputStream()的回复。
【解决方案2】:

这是在您的应用程序中使用的 doPostRequest() 方法,

这对你很有用,并且在我的代码中完美运行...

private void doPostRequest(){

    String urlString = "http://rasnacis.lv/vova.php";
    try
    {
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(urlString);

        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("email1_tag", new StringBody("email1_put_here"));
        reqEntity.addPart("email2_tag", new StringBody("email2_put)here"));
        reqEntity.addPart("email3_tag", new StringBody("email3_put_here"));
        post.setEntity(reqEntity);
        HttpResponse response = client.execute(post);
        resEntity = response.getEntity();
        final String response_str = EntityUtils.toString(resEntity);
        if (resEntity != null) {
            Log.i("RESPONSE",response_str);
            runOnUiThread(new Runnable(){
                public void run() {
                    try {
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
    catch (Exception ex){
        Log.e("Debug", "error: " + ex.getMessage(), ex);
    }
}

如果您实现此代码,您需要两个文件:

http://repo1.maven.org/maven2/org/apache/httpcomponents/httpmime/4.0.1/httpmime-4.0.1.jar

http://repo1.maven.org/maven2/org/apache/james/apache-mime4j/0.6/apache-mime4j-0.6.jar

【讨论】:

  • 你能告诉我,我需要在 MultipartEntity、StringBody 和 resEntity 的项目中包含什么,因为现在我对此有错误..
  • @vladimir 实际上你并不总是需要MultipartEntity。使用HttpEntity 它会为你做的
  • @pKs 好的,但是 resEntity 呢......它是什么类型或对象?
  • emmm,我对此代码有一些疑问,因为在我的情况下,程序挂在字符串 MultipartEntity reqEntity = new MultipartEntity();接下来什么也没有发生..
  • +1 HttpPost 自 android api 级别 21 起已弃用
猜你喜欢
  • 2016-11-19
  • 2012-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多