在android

时间:2017-06-05 22:33:24

标签: android web-services rest

我正在按照本教程调用android&中的Web服务它很棒,http://androidexample.com/Restful_Webservice_Call_And_Get_And_Parse_JSON_Data-_Android_Example/index.php?view=article_discription&aid=101

然而当我尝试使用此代码调用另一个Web服务时,只需更换serverURL,应用程序在pre-execute()中被阻止,任何人都可以告诉我还应该更改哪些内容?我以为所有的网络服务都有一个共同的代码?

mainActivity.java   



import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

public class MainActivity extends AppCompatActivity {

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

        Button GetData = (Button) findViewById(R.id.GetServerData);
        GetData.setOnClickListener(new View.OnClickListener() {
                                       @Override
                                       public void onClick(View v) {
                                           // WebServer Request URL
                                           String serverURL = "http://androidexample.com/media/webservice/JsonReturn.php";
                                           //  String serverURL = "http://hmkcode.appspot.com/rest/controller/get.json";
                                           // String serverURL="http://gdata.youtube.com/feeds/api/videos?q=Android&v=2&max-results=20&alt=jsonc&hl=en";

                                           // Use AsyncTask execute Method To Prevent ANR Problem
                                           new LongOperation().execute(serverURL);

                                       }
                                   }


        );
    }

    class LongOperation extends AsyncTask<String, Void, Void> {


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



        protected void onPreExecute() {
            // NOTE: You can call UI Element here.

            //Start Progress Dialog (Message)

            Dialog.setMessage("Please wait..");
            Dialog.show();


        }


        // 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);

                //String OutputData = MainActivity.parse(Content);

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


            }
        }






    }
}

1 个答案:

答案 0 :(得分:0)

我使用以下代码更改了发送PostRequest:// SEND获取数据请求HttpURLConnection conn =(HttpURLConnection)url.openConnection(); conn.setRequestMethod( “GET”);&安培;它的工作原理