简体   繁体   English

在Android应用上发出POST请求

[英]Make POST request on Android app

I know this has been asked before but I'm struggling.. I barely know any Java, but want an app so I can do my POST request without opening my website. 我知道以前曾有人问过这个问题,但我一直在努力。.我几乎不了解任何Java,但想要一个应用程序,这样我就可以在不打开网站的情况下进行POST请求。

So I've got this layout 所以我有这个布局

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:ems="10"
        android:inputType="textPersonName" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="Name:"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textSize="20dp" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText1"
        android:layout_below="@+id/editText1"
        android:ems="10"
        android:inputType="textPostalAddress" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignTop="@+id/editText2"
        android:text="Address:"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textSize="20dp" />

    <EditText
        android:id="@+id/editText3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/editText2"
        android:ems="10"
        android:inputType="phone" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/editText2"
        android:text="Phone:"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textSize="20dp" />

    <EditText
        android:id="@+id/editText4"
        android:layout_width="wrap_content"
        android:layout_height="200dp"
        android:layout_alignLeft="@+id/editText3"
        android:layout_below="@+id/editText3"
        android:ems="10"
        android:inputType="textMultiLine" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignTop="@+id/editText4"
        android:text="Comments:"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textSize="15dp" />

    <Button
        android:id="@+id/button1"
        android:layout_width="300dp"
        android:layout_height="50dp"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/editText4"
        android:layout_toLeftOf="@+id/editText4"
        android:text="Done"
        android:onClick="goToWeb(???);" />

</RelativeLayout>

and this Java: 和这个Java:

package com.example.request;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainRequest extends Activity {

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main_request, menu);
        return true;
    }

    public void goToWeb() {
        /* open webpage - how? */
    }
}

I want to make this POST request to http://www.example.com when they click Done: 当他们单击“完成”时,我想向http://www.example.com发出此POST请求:

name: (content of @+id/editText1)
addr: (content of @+id/editText2)
phone: (content of @+id/editText3)
comment: (content of @+id/editText4)

I want the phone's browser to open, and perform the POST request (if that makes sense) 我希望手机的浏览器打开,并执行POST请求(如果有意义)

How do I do this? 我该怎么做呢?

I feel this is a relevant question with a good answer that you may want to consider looking at. 我认为这是一个相关问题,您可能要考虑一下,并给出一个很好的答案。 Hope this helps. 希望这可以帮助。

Java - sending HTTP parameters via POST method easily Java-通过POST方法轻松发送HTTP参数

EDIT: Actually I found an ever better one for Android specifically: 编辑:实际上,我特别为Android找到了更好的一个:

Android, Java: HTTP POST Request Android,Java:HTTP POST请求

Okay so I guess you're also kinda confused about how to get the text from your text fields you created. 好的,我想您也对如何从创建的文本字段中获取文本感到困惑。 Here is another stackoverflow question that can help you: 这是另一个可以帮助您的stackoverflow问题:

Get Value of a Edit Text field 获取编辑文本字段的值

You have some edittext fields set up so you just have to store them in a variable (you can get that value by using findViewById(R.id.idOfEditText) and storing it in a variable. Now with that variable, you just need to call .getText() and then you have the String and can do whatever you need to do with it (such as sending it via POST). 您已经设置了一些edittext字段,因此只需将它们存储在变量中即可(您可以通过使用findViewById(R.id.idOfEditText)将该值存储在变量中。现在有了该变量,您只需要调用.getText() ,然后您就可以拥有String了,并且可以使用它进行任何处理(例如通过POST发送)。

Try this Class MainRequest 试试这个类MainRequest

package com.example.teststack;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;

public class MainRequest extends Activity {

    EditText textPersonName = null;
    EditText textPostalAddress = null;
    EditText phone = null;
    EditText textMultiLine = null;
    Button submit = null;
    String action = "http://www.omokoroacomputerhelp.com/";
    HttpPost httpRequest = null;
    List<NameValuePair> params = null;
    HttpResponse httpResponse = null;
    WebView webView = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_request);
        textPersonName = (EditText) findViewById(R.id.personName);
        textPostalAddress = (EditText) findViewById(R.id.postalAddress);
        phone = (EditText) findViewById(R.id.phone);
        textMultiLine = (EditText) findViewById(R.id.multiLine);
        submit = (Button) findViewById(R.id.submit);
        submit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                httpRequest = new HttpPost(action);
                params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("name", textPersonName
                        .getText().toString()));
                params.add(new BasicNameValuePair("phone", phone.getText()
                        .toString()));
                params.add(new BasicNameValuePair("addr", textPostalAddress
                        .getText().toString()));
                params.add(new BasicNameValuePair("comment", textMultiLine
                        .getText().toString()));
                try {
                    // send http request
                    httpRequest.setEntity(new UrlEncodedFormEntity(params,
                            HTTP.UTF_8));
                    // get http response
                    httpResponse = new DefaultHttpClient().execute(httpRequest);
                    //
                    Intent gotoIntent = new Intent(MainRequest.this,
                            Webpage.class);
                    gotoIntent.putExtra("source",
                            EntityUtils.toString(httpResponse.getEntity()));
                    startActivity(gotoIntent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main_request, menu);
        return true;
    }

}

and Webpage 和网页

package com.example.teststack;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.webkit.WebView;

public class Webpage extends Activity {
    WebView webView;

    final String mimeType = "text/html";

    final String encoding = "utf-8";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webpage);
        Intent webPageIntent = getIntent();
        String htmlSource = webPageIntent.getStringExtra("source");
        webView = (WebView) findViewById(R.id.webview);
        webView.loadData(htmlSource, mimeType, encoding);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_webpage, menu);
        return true;
    }
}

and activity_main_request.xml 和activity_main_request.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <EditText
        android:id="@+id/personName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:ems="10"
        android:inputType="textPersonName" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="Name:"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textSize="20dp" />

    <EditText
        android:id="@+id/postalAddress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/personName"
        android:layout_below="@+id/personName"
        android:ems="10"
        android:inputType="textPostalAddress" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignTop="@+id/postalAddress"
        android:text="Address:"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textSize="20dp" />

    <EditText
        android:id="@+id/phone"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/postalAddress"
        android:ems="10"
        android:inputType="phone" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/postalAddress"
        android:text="Phone:"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textSize="20dp" />

    <EditText
        android:id="@+id/multiLine"
        android:layout_width="wrap_content"
        android:layout_height="200dp"
        android:layout_alignLeft="@+id/phone"
        android:layout_below="@+id/phone"
        android:ems="10"
        android:inputType="textMultiLine" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignTop="@+id/multiLine"
        android:text="Comments:"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textSize="15dp" />

    <Button
        android:id="@+id/submit"
        android:layout_width="300dp"
        android:layout_height="50dp"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/multiLine"
        android:layout_toLeftOf="@+id/multiLine"
        android:text="Done" />

</RelativeLayout>

and activity_webpage.xml 和activity_webpage.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

   <WebView  
        android:id="@+id/webview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        />

</RelativeLayout>

and AndroidManifest.xml 和AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.teststack"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainRequest"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Webpage"
            android:label="@string/title_activity_webpage" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Try using the NameValuePair .. I am giving the code which i used in my app to do Http Post 尝试使用NameValuePair ..我给出了我在应用程序中用于执行Http Post的代码

public String postData(String url, String xmlQuery) {



        final String urlStr = url;
        final String xmlStr = xmlQuery;
        final StringBuilder sb  = new StringBuilder();


        Thread t1 = new Thread(new Runnable() {

            public void run() {

                HttpClient httpclient = MySSLSocketFactory.getNewHttpClient();

                HttpPost httppost = new HttpPost(urlStr);


                try {

                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
                            1);
                    nameValuePairs.add(new BasicNameValuePair("xml", xmlStr));

                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                    HttpResponse response = httpclient.execute(httppost);

                    Log.d("Vivek", response.toString());

                    HttpEntity entity = response.getEntity();
                    InputStream i = entity.getContent();

                    Log.d("Vivek", i.toString());
                    InputStreamReader isr = new InputStreamReader(i);

                    BufferedReader br = new BufferedReader(isr);

                    String s = null;


                    while ((s = br.readLine()) != null) {

                        Log.d("YumZing", s);
                        sb.append(s);
                    }


                    Log.d("Check Now",sb+"");




                } catch (ClientProtocolException e) {

                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        });

        t1.start();
        try {
            t1.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        System.out.println("Getting from Post Data Method "+sb.toString());

        return sb.toString();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM