簡體   English   中英

Android AsyncTask通過http Post發送數據

[英]Android AsyncTask sending data via http Post

我有這個腳本。

我已經經歷了堆棧溢出問題的許多變化,並使用解決方案嘗試構建知識來做到這一點,但它似乎每次都失敗,有人可以幫忙嗎?

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
            }
        }   
    }
}

我在網上找到了這個代碼,我只是想讓它工作,所以我有一個工作原型來解決並構建我自己的但我一直在我的日志文件中得到這個:

    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$3.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$1.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$2.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

表現

<?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>

互聯網權限設置,我已查找異常,但答案似乎與我的代碼,任何想法無關?

線索在logcat中:

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

您在AndroidManifest中缺少android.permission.INTERNET權限。 添加此行:

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

略低於:

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="18" />
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
    }
}

試試這種方式。

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文件更改

    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')

//添加列表

ListView列表視圖; ArrayList mylistname = new ArrayList <>(); ArrayList mylistnum = new ArrayList <>();

mylistname.add( “阿米特”); mylistnum.add( “7042757424”);

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

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

//適配器集數據項public class MyArrayAdapter實現ListAdapter {Activity activity; int size; 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;
}

}

使用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類

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();
}

}

添加依賴關系如下

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM