简体   繁体   English

Android使用Rest API

[英]Android using rest api

How to post the data dynamically from the get method to post method pls, help me to solve this issue.in the url1 I have to store the data in DB when I used to select the email id the particular physician key and the email id should be stored in DB 如何从get方法到post方法pls动态地发布数据,帮助我解决了这个问题。在url1中,当我用来选择特定医生密钥和电子邮件ID的电子邮件ID时,我必须将数据存储在DB中存储在数据库中

                   if (jsonString1 != null) {
                       try {
                           JSONObject jsonObject1 = new JSONObject(jsonString1);
                           // Getting JSON Array node
                           JSONArray contacts1 = jsonObject1.getJSONArray("physicianlist");

                           for (int i = 0; i < contacts1.length(); i++) {
                               JSONObject c = contacts1.getJSONObject(i);

                               String Name = c.getString("Name");

                               String Physician_Key = c.getString("Physician_Key");

                               myIntArray[i]=Physician_Key;
                               String Specialization = c.getString("Specialization");
                               String ProviderName = c.getString("ProviderName");
                               String EmailId = c.getString("EmailId");
                               String Location = c.getString("Location");    
                               HashMap<String, String> phy = new HashMap<>();
                               // adding each child node to HashMap key => value
                               phy.put("Name", Name);
                               phy.put("Physician_Key", Physician_Key);
                               phy.put("Specialization", Specialization);
                               phy.put("ProviderName",ProviderName);
                               phy.put("EmailId",EmailId);
                               phy.put("Location",Location);
                               al.add(EmailId);

                               // adding contact to contact list
                               phyJsonList.add(phy);
                           }
               } catch (final JSONException e) {
                   Log.e(TAG, "Json parsing error: " + e.getMessage());
                   runOnUiThread(new Runnable() {
                       @Override
                       public void run() {
                           Toast.makeText(getApplicationContext(),
                                   "Json parsing error: " + e.getMessage(),
                                   Toast.LENGTH_LONG)
                                   .show();
                       }
                   }); }
           } else {Log.e(TAG, "Could not get json from server.");
               runOnUiThread(new Runnable() {
                   @Override
                   public void run() {
                       Toast.makeText(getApplicationContext(),
                               "Could not get json from server.",
                            Toast.LENGTH_LONG)
                               .show();
                   }
               });

           }

           return null;
       }

       @Override
       protected void onPostExecute(Void result) {
           super.onPostExecute(result);
           // Dismiss the progress dialog
           if (progressDialog.isShowing())
               progressDialog.dismiss();
           /**
            * Updating parsed JSON data into ListView
            * */

          ListAdapter adapter1 = new SimpleAdapter(
                  MainActivity.this,phyJsonList ,
                 R.layout.list_item2, new String[]{"Name", "Physician_Key",
                  "Specialization","ProviderName","EmailId","Location"}, new
                   int[]{R.id.Name,
                  R.id.Physician_key, 

   R.id.Specialization,R.id.ProviderName,R.id.EmailId,R.id.Location});


           listView.setAdapter(adapter);
          listView1.setAdapter(adapter1);
           Utility.setListViewHeightBasedOnChildren(listView);
           Utility.setListViewHeightBasedOnChildren(listView1);
       }

   }

   public class SendPostRequest extends AsyncTask<String, Void, String> {

       protected void onPreExecute(){}

       protected String doInBackground(String... arg0) {

           try {
               URL url = new URL("https://example.com");
               URL url1 = new URL("https://xyz.sharedinfo"); // here is your URL path

               final JSONObject postDataParams = new JSONObject();
               final JSONObject postDataParams1=new JSONObject();
             /*  postDataParams.put("name", "abc");
               postDataParams.put("email", "abc@gmail.com");*/ //here i have to post the data dynamically
               postDataParams1.put("PhysicianKey","55") ;
               postDataParams1.put("PatientKey", "5010");
               postDataParams.put("Email","john@john.com");


               runOnUiThread(new Runnable() {
                   @Override
                   public void run() {
                       Toast.makeText(MainActivity.this, postDataParams.toString(), Toast.LENGTH_SHORT).show();
                   }
               });


               Log.e("params",postDataParams.toString());

               HttpURLConnection conn = (HttpURLConnection) url.openConnection();
               HttpURLConnection conn1 = (HttpURLConnection) url1.openConnection();

               conn.setReadTimeout(15000 /* milliseconds */);
               conn.setConnectTimeout(15000 /* milliseconds */);
               conn.setRequestMethod("POST");
               conn.setDoInput(true);
               conn.setDoOutput(true);
               conn1.setReadTimeout(15000 /* milliseconds */);
               conn1.setConnectTimeout(15000 /* milliseconds */);
               conn1.setRequestMethod("POST");
               conn1.setDoInput(true);
               conn1.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()-1;

               // if (responseCode == HttpsURLConnection.HTTP_OK) {

               BufferedReader in=new BufferedReader(new InputStreamReader(conn.getInputStream()));

               StringBuffer sb = new StringBuffer("");
               String line="";

               while((line = in.readLine()) != null) {

                   sb.append(line);
                   break;
               }

               in.close();
               return sb.toString();

               //  }
              /* else {
                   return new String("false : "+responseCode);
               }*/
           }
           catch(Exception e){
               return new String("Exception: " + e.getMessage());
           }

       }

       @Override
       protected void onPostExecute(String result) {
           Toast.makeText(getApplicationContext(), result,
                   Toast.LENGTH_LONG).show();
       }
   }

   public String getPostDataString(JSONObject params) throws Exception {

       StringBuilder result = new StringBuilder();
       boolean first = true;

       Iterator<String> itr = params.keys();

       while(itr.hasNext()){

           String key= itr.next();
           Object value = params.get(key);

           if (first)
               first = false;
           else
               result.append("&");

           result.append(URLEncoder.encode(key,"UTF-8"));
           result.append("=");
           result.append(URLEncoder.encode(value.toString(),"UTF-8"));
       }
       return result.toString();
   } }

you can use volley for handle http request In android studio -put this line in your build.gradle 您可以使用volley处理http请求在android studio中-在build.gradle中放入这一行

dependencies{
compile 'com.mcxiaoke.volley:library-aar:1.0.0'
}

Use this method (post) call this method 使用此方法(发布)调用此方法

public void postData(){

  StringRequest stringRequest = new StringRequest(Request.Method.POST, "YOUR URL",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jobject = new JSONObject(response);
                            Log.e("jobject ", jobject + "<return");
                        }catch (JSONException je){

                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getActivity(),error.toString(),Toast.LENGTH_LONG).show();
                    }
                }){
            @Override
            protected Map<String,String> getParams(){
                Map<String,String> params = new HashMap<String, String>();
                params.put("Name","Mr.Lavanya");
                params.put("Physician_Key", "Physician_Key");
                params.put("ProviderName","ProviderName");
                params.put("EmailId","EmailId");
                params.put("Location","Location"), 

                Log.e("params",params+"");
                return params;
            }
        };

        RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
        requestQueue.add(stringRequest);
}

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

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