2017-04-18 56 views
1

我的知识在android中非常有限我是newBi,有谁能告诉我如何获得JSON的响应和发布信息....如果您有建议,请编辑我的代码并插入一个评论,以便我可以确定我缺少的方法。 我无法分析一些发布的相关问题,我已经做了我的研究,但我无法完善它。如果我的代码错误或不完整,请纠正我。Android http POST回复

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

首先看你的代码,我会建议你使用'retrofit'或'httpOk'的API – KOTIOS

+0

@MyMasterPeice你能给我例子是什么? – koroku

回答

0

用于经由retrofit获取数据的简单示例:

注意:此API在后台线程中运行,因此不调用从任何其他后台线程该方法类似的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 
     } 
    } 

和下面是如何通过界面创建发布请求:

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

做以下改进的lib更新您的gradle产出:

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

我不明白...你能更清楚地解释它吗? – koroku

+0

首先你需要创建接口,你提到如果得到或发布和传递参数如上所述'getClinics(@Field(Constants.APPOINTMENT_DOCTOR_ID)String doctorId);'这将返回你模型的json'ClinicsModel' – KOTIOS

+0

其次,你将导入retorifit库如上所述,并将调用API如上所述,你得到的答复在失败或成功 – KOTIOS