Android AsyncTask 通过 http Post 发送数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21418349/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 04:33:01  来源:igfitidea点击:

Android AsyncTask sending data via http Post

androidandroid-asynctaskhttprequest

提问by Random_Guy_a

I have this script.

我有这个脚本。

I have gone through many variations of the problem on stack overflow and used the solution to try and build the knowledge to do this but it seems to be failing everytime, can someone help?

我经历了堆栈溢出问题的许多变化,并使用该解决方案尝试建立知识来做到这一点,但似乎每次都失败了,有人可以帮忙吗?

public class Main extends Activity implements OnClickListener {

    private EditText value;
    private Button btn;
    private ProgressBar pb;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        value = (EditText) findViewById(R.id.editText1);
        btn = (Button) findViewById(R.id.button1);
        pb = (ProgressBar) findViewById(R.id.progressBar1);
        pb.setVisibility(View.GONE);
        btn.setOnClickListener(this);
    }

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

    public void onClick(View v) {
        // TODO Auto-generated method stub
        if (value.getText().toString().length() < 1) {
            // out of range
            Toast.makeText(this, "please enter something", Toast.LENGTH_LONG)
                    .show();
        } else {
            pb.setVisibility(View.VISIBLE);
            new MyAsyncTask().execute("hey");
        }

    }

    private class MyAsyncTask extends AsyncTask<String, Integer, Double> {

        @Override
        protected Double doInBackground(String... params) {
            // TODO Auto-generated method stub
            postData(params[0]);
            return null;
        }

        protected void onPostExecute(Double result) {
            pb.setVisibility(View.GONE);
            Toast.makeText(getApplicationContext(), "command sent",
                    Toast.LENGTH_LONG).show();
        }

        protected void onProgressUpdate(Integer... progress) {
            pb.setProgress(progress[0]);
        }

        public void postData(String valueIWantToSend) {
            // Create a new HttpClient and Post Header
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(
                    "http://users.aber.ac.uk/bym1/group/androidto.php");

            try {
                // Add your data
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("myHttpData",
                        valueIWantToSend));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                // Execute HTTP Post Request
                HttpResponse response = httpclient.execute(httppost);

            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
            } catch (IOException e) {
                // TODO Auto-generated catch block
            }
        }   
    }
}

I found this code on the net and I'm just trying to get it to work so i have a working prototype to work off and build my own but I keep getting this in my log file:

我在网上找到了这段代码,我只是想让它工作,所以我有一个工作原型可以工作并构建我自己的,但我一直在我的日志文件中得到这个:

    01-28 22:30:07.030: W/dalvikvm(27142): threadid=11: thread exiting with uncaught exception (group=0x40bc2498)
01-28 22:30:07.030: E/test(27142): Exception
01-28 22:30:07.060: E/AndroidRuntime(27142): FATAL EXCEPTION: AsyncTask #1
01-28 22:30:07.060: E/AndroidRuntime(27142): java.lang.RuntimeException: An error occured while executing doInBackground()
01-28 22:30:07.060: E/AndroidRuntime(27142):    at android.os.AsyncTask.done(AsyncTask.java:299)
01-28 22:30:07.060: E/AndroidRuntime(27142):    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
01-28 22:30:07.060: E/AndroidRuntime(27142):    at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
01-28 22:30:07.060: E/AndroidRuntime(27142):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
01-28 22:30:07.060: E/AndroidRuntime(27142):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-28 22:30:07.060: E/AndroidRuntime(27142):    at android.os.AsyncTask$SerialExecutor.run(AsyncTask.java:230)
01-28 22:30:07.060: E/AndroidRuntime(27142):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
01-28 22:30:07.060: E/AndroidRuntime(27142):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
01-28 22:30:07.060: E/AndroidRuntime(27142):    at java.lang.Thread.run(Thread.java:856)
01-28 22:30:07.060: E/AndroidRuntime(27142): Caused by: java.lang.SecurityException: Permission denied (missing INTERNET permission?)
01-28 22:30:07.060: E/AndroidRuntime(27142):    at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
01-28 22:30:07.060: E/AndroidRuntime(27142):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
01-28 22:30:07.060: E/AndroidRuntime(27142):    at java.net.InetAddress.getAllByName(InetAddress.java:214)
01-28 22:30:07.060: E/AndroidRuntime(27142):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
01-28 22:30:07.060: E/AndroidRuntime(27142):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
01-28 22:30:07.060: E/AndroidRuntime(27142):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
01-28 22:30:07.060: E/AndroidRuntime(27142):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
01-28 22:30:07.060: E/AndroidRuntime(27142):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
01-28 22:30:07.060: E/AndroidRuntime(27142):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
01-28 22:30:07.060: E/AndroidRuntime(27142):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
01-28 22:30:07.060: E/AndroidRuntime(27142):    at com.example.httpasync.Main$MyAsyncTask.postData(Main.java:98)
01-28 22:30:07.060: E/AndroidRuntime(27142):    at com.example.httpasync.Main$MyAsyncTask.doInBackground(Main.java:70)
01-28 22:30:07.060: E/AndroidRuntime(27142):    at com.example.httpasync.Main$MyAsyncTask.doInBackground(Main.java:1)
01-28 22:30:07.060: E/AndroidRuntime(27142):    at android.os.AsyncTask.call(AsyncTask.java:287)
01-28 22:30:07.060: E/AndroidRuntime(27142):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-28 22:30:07.060: E/AndroidRuntime(27142):    ... 5 more
01-28 22:30:07.060: E/AndroidRuntime(27142): Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)
01-28 22:30:07.060: E/AndroidRuntime(27142):    at libcore.io.Posix.getaddrinfo(Native Method)
01-28 22:30:07.060: E/AndroidRuntime(27142):    at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:55)
01-28 22:30:07.060: E/AndroidRuntime(27142):    at java.net.InetAddress.lookupHostByName(InetAddress.java:405)
01-28 22:30:07.060: E/AndroidRuntime(27142):    ... 19 more
01-28 22:30:07.060: E/AndroidRuntime(27142): Caused by: libcore.io.ErrnoException: getaddrinfo failed: EACCES (Permission denied)
01-28 22:30:07.060: E/AndroidRuntime(27142):    ... 22 more

Manifest

显现

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.httpasync"
    android:versionCode="1"
    android:versionName="1.0" >

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.httpasync.Main"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

Internet permissions are set, I have looked up the exceptions but the answers dont seem to relate to my code, any ideas?

设置了 Internet 权限,我查找了例外情况,但答案似乎与我的代码无关,有什么想法吗?

回答by Melquiades

The clue is in the logcat:

线索在logcat中:

Caused by: java.lang.SecurityException: Permission denied (missing INTERNET permission?)

You are missing android.permission.INTERNETpermission in your AndroidManifest. Add this line:

android.permission.INTERNET的 AndroidManifest中缺少权限。添加这一行:

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

just below:

略低于:

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

回答by Hardik Karkar

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_insert);

    edtisdn=(EditText)findViewById(R.id.edtisdn);
    edttitle=(EditText)findViewById(R.id.edttitle);
    edtauthor=(EditText)findViewById(R.id.edtauthor);
    edtprice=(EditText)findViewById(R.id.edtprice);

    btnsubmit=(Button)findViewById(R.id.btnsubmit);

    btnsubmit.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

             bisdn=edtisdn.getText().toString();
             btitle=edttitle.getText().toString();
             bauthor=edtauthor.getText().toString();
             bprice=edtprice.getText().toString();

            /*Database databse=new Database(InsertActivity.this);
            databse.open();
            databse.insertData(bisdn,btitle,bauthor,bprice);
            databse.close();*/

            new inserttask().execute();
        }
    });
}

class inserttask extends AsyncTask<Void, Void, Void>{

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
    }
    @Override
    protected Void doInBackground(Void... params) {
        // TODO Auto-generated method stub
        insert_to_server();
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
    }
}

public void insert_to_server(){

    HttpClient httpclient=new DefaultHttpClient();

    HttpPost httppost=new HttpPost("http://192.168.1.13/mywebservice/insert_book.php");

    try {

        List<NameValuePair> namevaluepair=new ArrayList<NameValuePair>(4);

        namevaluepair.add(new BasicNameValuePair("isdn", bisdn));
        Log.d("isdn",bisdn);
        namevaluepair.add(new BasicNameValuePair("title", btitle));
        Log.d("title",btitle);
        namevaluepair.add(new BasicNameValuePair("author", bauthor));
        Log.d("author",bauthor);
        namevaluepair.add(new BasicNameValuePair("price", bprice));
        Log.d("price",bprice);


        httppost.setEntity(new UrlEncodedFormEntity(namevaluepair));
        HttpResponse httpresponse=httpclient.execute(httppost);
        int status=httpresponse.getStatusLine().getStatusCode();
        Log.d("status",status+"");
    } catch (Exception e) {
        // TODO: handle exception
    }
}

回答by Amitsharma

try with this way .

用这种方式试试。

String BASEURL = "http://androidexample.com/media/webservic/JsonReturn.php";

String BASEURL = " http://androidexample.com/media/webservic/JsonReturn.php";

Context context;
public static final String FILTER = "just.a.filter";
public static final String KEY = "key";
private int REQUEST_PERMISSION_PHONE_STATE = 1;
private LinearLayout llDashMenu; 
// new LongOperation().execute(BASEURL);
 private class LongOperation extends AsyncTask<String, Void, Void> {
    // Required initialization
    private final HttpClient Client = new DefaultHttpClient();
    private String Content;
    private String Error = null;
    private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
    String data = "";
    TextView uiUpdate = (TextView) findViewById(R.id.output);
    TextView jsonParsed = (TextView) findViewById(R.id.jsonParsed);
    int sizeData = 0;
    EditText serverText = (EditText) findViewById(R.id.serverText);

    protected void onPreExecute() {
        Dialog.setMessage("Please wait..");
        Dialog.show();
        try {
            data += "&" + URLEncoder.encode("data", "UTF-8") + "=" + serverText.getText();

        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    // Call after onPreExecute method
    protected Void doInBackground(String... urls) {

        /************ Make Post Call To Web Server ***********/
        BufferedReader reader = null;

        // Send data
        try {
            // Defined URL  where to send data
            URL url = new URL(urls[0]);
            // Send POST data request
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(data);
            wr.flush();

            // Get the server response

            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line = null;

            // Read Server Response
            while ((line = reader.readLine()) != null) {
                // Append server response in string
                sb.append(line + " ");
            }

            // Append Server Response To Content String
            Content = sb.toString();
        } catch (Exception ex) {
            Error = ex.getMessage();
        } finally {
            try {

                reader.close();
            } catch (Exception ex) {
            }
        }

        /*****************************************************/
        return null;
    }

    protected void onPostExecute(Void unused) {
        // NOTE: You can call UI Element here.

        // Close progress dialog
        Dialog.dismiss();

        if (Error != null) {

            uiUpdate.setText("Output : " + Error);

        } else {

            // Show Response Json On Screen (activity)
            uiUpdate.setText(Content);

            /****************** Start Parse Response JSON Data *************/

            String OutputData = "";
            JSONObject jsonResponse;

            try {

                /****** Creates a new JSONObject with name/value mappings from the JSON string. ********/
                jsonResponse = new JSONObject(Content);

                /***** Returns the value mapped by name if it exists and is a JSONArray. ***/
                /*******  Returns null otherwise.  *******/
                JSONArray jsonMainNode = jsonResponse.optJSONArray("Android");

                /*********** Process each JSON Node ************/

                int lengthJsonArr = jsonMainNode.length();

                for (int i = 0; i < lengthJsonArr; i++) {
                    /****** Get Object for each JSON node.***********/
                    JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);

                    /******* Fetch node values **********/
                    String name = jsonChildNode.optString("name").toString();
                    String number = jsonChildNode.optString("number").toString();
                    String date_added = jsonChildNode.optString("date_added").toString();


                }
                /****************** End Parse Response JSON Data *************/

                //Show Parsed Output on screen (activity)
                jsonParsed.setText(OutputData);


            } catch (JSONException e) {

                e.printStackTrace();
            }
        }
    }

}

Gradle file changes

Gradle 文件更改

    compileSdkVersion 24
    buildToolsVersion '23.0.3'
    minSdkVersion 16
    targetSdkVersion 24
    versionCode 1
    versionName "1.0"

 compile 'com.android.support:appcompat-v7:24.2.1'
testCompile 'junit:junit:4.12'

compile files('libs/httpcore-4.0.1.jar')
compile files('libs/httpclient-4.2.jar')
compile files('libs/httpmime-4.2.1-1.jar')

// add on list

// 添加到列表中

ListView listview; ArrayList mylistname=new ArrayList<>(); ArrayList mylistnum=new ArrayList<>();

列表视图列表视图;ArrayList mylistname=new ArrayList<>(); ArrayList mylistnum=new ArrayList<>();

mylistname.add("amit"); mylistnum.add("7042757424");

mylistname.add("amit"); mylistnum.add("7042757424");

    mylistname.add("amitt");
    mylistnum.add("7042757469");

    mylistname.add("amitdd");
    mylistnum.add("7042757444");
     listview.setAdapter(new 
     MyArrayAdapter(MainActivity.this,mylistname,mylistnum));

// adapter set data items public class MyArrayAdapter implements ListAdapter { Activity activity; int size; ArrayList mylistname,mylistnum;

// 适配器集数据项 public class MyArrayAdapter 实现 ListAdapter { Activity activity; 整数大小;ArrayList mylistname,mylistnum;

public MyArrayAdapter(Activity activity,
    ArrayList<String> mylistname, ArrayList<String> mylistnum) {
// TODO Auto-generated constructor stub
this.mylistnum=mylistnum;
this.mylistname=mylistname;
this.activity=activity;

size=mylistname.size();

}

@SuppressWarnings("static-access")
@Override
public View getView(int position, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub


LayoutInflater inflater = (LayoutInflater) activity
    .getSystemService(activity.LAYOUT_INFLATER_SERVICE);

View v=inflater.inflate(R.layout.mylayout, null);
TextView tviname=(TextView)v.findViewById(R.id.tviname);
TextView tviphone=(TextView)v.findViewById(R.id.tviphone);


tviname.setText(mylistname.get(position));
tviphone.setText(mylistnum.get(position));


return v;
}


@Override
public void registerDataSetObserver(DataSetObserver observer) {
    // TODO Auto-generated method stub

}

@Override
public void unregisterDataSetObserver(DataSetObserver observer) {
    // TODO Auto-generated method stub

}

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return size;
}

@Override
public Object getItem(int position) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public long getItemId(int position) {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public boolean hasStableIds() {
    // TODO Auto-generated method stub
    return false;
}



@Override
public int getItemViewType(int position) {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public int getViewTypeCount() {
    // TODO Auto-generated method stub
    return size;
}

@Override
public boolean isEmpty() {
    // TODO Auto-generated method stub
    return false;
}

@Override
public boolean areAllItemsEnabled() {
    // TODO Auto-generated method stub
    return false;
}

@Override
public boolean isEnabled(int position) {
    // TODO Auto-generated method stub
    return false;
}

}

}

回答by Mahesh Pandit

to post using asychtask can done by follow

使用 asychtask 发布可以通过以下方式完成

class AsynTask extends AsyncTask<Void, Void, String> {
    ProgressDialog loading;

    @Override
    protected String doInBackground(Void... params) {
        RequestHandler rh = new RequestHandler() {
            public boolean canHandleRequest(Request data) {
                return false;
            }
            public Result load(Request request, int networkPolicy) throws IOException {
                return null;
            }
        };
        HashMap<String, String> param = new HashMap<String, String>();
        param.put("phone", "8888888888");
        param.put("token", "1234567890");

        String result = rh.sendPostRequest("\n" +
                "GIVEN_API", param);
        Log.i("result", result);
        return result;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        loading = ProgressDialog.show(mContext, "Please wait...", "Loading", false, false);
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        Log.i("stauts", s);
        String status = null;
        try {
            JSONObject mainObject = new JSONObject(s);
            status = mainObject.getString("status");

            Log.i("output", status);
            if(status.equals("true")){
            Toast.makeText(mContext," successfully",Toast.LENGTH_SHORT).show();

            }else {
                Toast.makeText(mContext,"Please try again",Toast.LENGTH_SHORT).show();
            }

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


        loading.dismiss();

    }
}

httphandler class

httphandler 类

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;

public class RequestHandler {

public String sendPostRequest(String requestURL,
                              HashMap<String, String> postDataParams) {

    URL url;

    StringBuilder sb = new StringBuilder();
    try {
        url = new URL(requestURL);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(1500000);
        conn.setConnectTimeout(1500000);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);


        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(os, "UTF-8"));
        writer.write(getPostDataString(postDataParams));

        writer.flush();
        writer.close();
        os.close();
        int responseCode = conn.getResponseCode();

        if (responseCode == HttpsURLConnection.HTTP_OK) {
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            sb = new StringBuilder();
            String response;
            while ((response = br.readLine()) != null){
                sb.append(response);
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return sb.toString();
}

private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
    StringBuilder result = new StringBuilder();
    boolean first = true;
    for (Map.Entry<String, String> entry : params.entrySet()) {
        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
    }

    return result.toString();
}

}

add dependency as follow

添加依赖如下

compile 'org.apache.httpcomponents:httpclient:jar:4.5.2'
compile 'org.apache.httpcomponents:httpcore:4.4.1'