2017-04-18 4 views
1

Mein Wissen ist sehr begrenzt in android Ich bin newBi, kann mir jemand sagen, wie bekomme ich die Antwort und Post von JSON, die ich bekomme .... Wenn Sie einen Vorschlag haben nur meinen Code bearbeiten und einfügen ein Kommentar, damit ich meine fehlenden Methoden identifizieren kann. Ich kann einige gepostete Fragen nicht analysieren, ich forsche bereits, aber ich kann es nicht perfektionieren. Korrigiere mich, wenn mein Code falsch oder unvollständig ist.Android http POST Antwort

public void httpConnection(HashMap<String, String> postDataParams) { 

    HttpURLConnection httpcon; 
    String url = "(url here...)"; 
    String result; 
    try { 

     httpcon = (HttpURLConnection) ((new URL(url).openConnection())); 
     httpcon.setDoOutput(true); 
     httpcon.setRequestProperty("Key", "Value"); 
     httpcon.setRequestProperty("action", "get_scoop"); 
     httpcon.setRequestMethod("POST"); 

     httpcon.connect(); 


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


     BufferedReader br = new BufferedReader(new InputStreamReader(httpcon.getInputStream(), "UTF-8")); 

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

     while ((line = br.readLine()) != null) { 
      sb.append(line); 
     } 

     br.close(); 
     result = sb.toString(); 

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


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

public class CallAPI extends AsyncTask<String, String, String> { 

    public CallAPI() { 
     //set context variables if required 
    } 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
    } 


    @Override 
    protected String doInBackground(String... params) { 

     String urlString = params[0]; // URL to call 

     String resultToDisplay = ""; 

     InputStream in = null; 
     try { 

      URL url = new URL(urlString); 

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


      in = new BufferedInputStream(urlConnection.getInputStream()); 


     } catch (Exception e) { 

      Log.e("TAG", e.getMessage()); 


      return e.getMessage(); 

     } 

     try { 
       resultToDisplay = IOUtils.toString(in, "UTF-8"); 
      //to [convert][1] byte stream to a string 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     return resultToDisplay; 
    } 


    @Override 
    protected void onPostExecute(String result) { 
     //Update the UI 
    } 
} 
+0

zunächst bei Ihrem Code suchen würde ich Ihnen vorschlagen, verwenden 'retrofit' oder' httpOk' apis – KOTIOS

+0

@MyMasterPeice können Sie mir Beispiel dafür geben? – koroku

Antwort

0

Ein einfaches Beispiel für Daten, die über retrofit Abrufen:

Hinweis: Diese API läuft im Hintergrund-Thread somit kann dieses Verfahren nicht Anruf von jedem anderen Hintergrund-Thread wie AsyncTask

private void fetchDoctorClinics() { 
     if (EasyPadhaiUtils.checkInternetConnection(DoctorDashbaord.this)) { 

      // State Callback 
      retrofit2.Callback callback = new retrofit2.Callback<ClinicsModel>() { 
       @Override 
       public void onResponse(Call<ClinicsModel> call, Response<ClinicsModel> response) { 


       } 

       @Override 
       public void onFailure(Call<ClinicsModel> call, Throwable t) { 

       } 
      }; 

      Retrofit retrofit = new Retrofit.Builder() 
        .baseUrl(Constants.DOMAIN_URL) 
        .addConverterFactory(GsonConverterFactory.create()) 
        .build(); 

      // prepare call in Retrofit 2.0 
      ClinicsInterface clinicsInterface = retrofit.create(ClinicsInterface.class); 
      Call<ClinicsModel> call = clinicsInterface.getClinics("10"); 
      call.enqueue(callback); 
     } else { 
      // Network not available , handle this 
     } 
    } 

und unten ist Wie Sie eine Postanforderung über die Schnittstelle erstellen:

public interface ClinicsInterface { 
    @FormUrlEncoded 
    @POST(Constants.CONTROLLER_API) 
    Call<ClinicsModel> getClinics(@Field(Constants.APPOINTMENT_DOCTOR_ID) String doctorId); 
} 

Do Ihre gradle mit unter Retrofit lib aktualisieren:

compile 'com.google.code.gson:gson:2.6.2' 
    compile 'com.squareup.retrofit2:retrofit:2.1.0' 
    compile 'com.squareup.retrofit2:converter-gson:2.1.0' 
+0

Ich verstehe es nicht ... können Sie es deutlicher erklären? – koroku

+0

Zuerst müssen Sie Schnittstelle erstellen, wo Sie erwähnen, wenn Get oder Post und übergeben Params wie oben erwähnt 'getClinics (@Field (Constants.APPOINTMENT_DOCTOR_ID) Zeichenfolge doctorId);' die gibt Ihnen das Modell von JSON 'ClinicsModel' – KOTIOS

+0

zweitens werden Sie importieren retorifit libs wie oben erwähnt und rufen Sie API wie oben erwähnt, wo Sie entweder im Fehler oder Erfolg Antwort bekommen – KOTIOS