1

我无法从我的 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开发,不知道很多技巧或困难的东西......

4

2 回答 2

13

我已经使用这种技术使用 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" />
于 2013-02-26T06:32:04.863 回答
4

这是在您的应用程序中使用的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

于 2013-02-26T06:35:32.360 回答