2016-03-31 4 views
-2

için Ayrıntılı olarak HttpUrlConnection kullanarak parametreleri içeren yazı isteğinde nasıl. Giriş ekranında kullanıcı adı, parola alanı, sunucuya posta göndermek ve "TRUE" durumuyla json yanıtı olsun. Volley Kütüphanesi kullanmak istemiyorum.
Lütfen ayrıntılı bir şekilde cevap verin veya bağlantı paylaşın, teşekkürler u.<em>anahtarı HttpUrlConnection kullanarak</em> parametreler değer çifti ile <code>POST Request</code> için <strong>iyi cevap</strong> paylaşın android

+4

kendi başınıza çalıştık ne olacak? Veya Google.com’u da yapın. –

+2

'stack.com 'adresini tarayıcınızda' Google.com' yerine 'google.com' olarak girdiniz. –

+0

@jaydroider HashMap ile çalıştım params çok iyi çalışıyor. Ama doğru yol olup olmadığını bilmiyorum. Kullanımdan kaldırılan HttpClient'i kullandıkları çok öğretici arandı. lütfen mükemmel bir yanıtı paylaşın veya –

cevap

1

aşağıdaki kodla bir dize isteği hazırlayın:

Uri.Builder builder = new Uri.Builder() 
         .appendQueryParameter("username", edit_username.getText().toString()) 
         .appendQueryParameter("password", edit_password.getText().toString()); 

        String query = builder.build().getEncodedQuery(); 

koduyla takip ederek tüm zaman uyumsuz görev web hizmeti gerçekleştirin:

new AsyncLoad(query).execute(); // You have pass your request here 

: Aşağıdaki çizgi ile

class AsyncLoad extends AsyncTask<Void,Void,Void> 
{ 

    InputStream inputStream; 
    HttpURLConnection urlConnection; 
    byte[] outputBytes; 
    String query; 
    String ResponseData; 

    public AsyncLoad(String query) { 
     this.query = query; 
    } 

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

     // Send data 
     try { 

     /* forming th java.net.URL object */ 
      URL url = new URL("your webservice url"); 
      urlConnection = (HttpURLConnection) url.openConnection(); 


      /* pass post data */ 
      outputBytes = query.getBytes("UTF-8"); 

      urlConnection.setRequestMethod("POST"); 
      urlConnection.connect(); 
      OutputStream os = urlConnection.getOutputStream(); 
      os.write(outputBytes); 
      os.close(); 

     /* Get Response and execute WebService request*/ 
      int statusCode = urlConnection.getResponseCode(); 

     /* 200 represents HTTP OK */ 
      if (statusCode == HttpsURLConnection.HTTP_OK) { 

       inputStream = new BufferedInputStream(urlConnection.getInputStream()); 
       ResponseData= convertStreamToString(inputStream); 

      } else { 

       ResponseData = null; 
      } 


     } catch (Exception e) { 

      e.printStackTrace(); 

     } 



     return null; 
    } 
} 

Çağrı AsynctTask Yanıtı String'e dönüştür:

public static String convertStreamToString(InputStream is) { 

     BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
     StringBuilder sb = new StringBuilder(); 

     String line = null; 
     try { 
      while ((line = reader.readLine()) != null) { 
       sb.append((line + "\n")); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       is.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
     return sb.toString(); 
    } 
+0

bağlantısını nasıl outputBytes? Metot veya sınıfa istek kodu koyabilir miyim, sorguyu bu yönteme nasıl aktarabilirim, lütfen ayrıntılı olarak cevap verin. Cevabınızı –

+0

dünya çapında declare byte [] outputBytes değişkeni kabul ediyorum. Sorgulayıcısını kullanarak parametreyi ileterek sorguyu async sınıfınıza aktarabilirsiniz. Eşzamansız görevi nasıl kullanacağınız hakkında bilgi edinebilirsiniz: http://developer.android.com/intl/zh-cn/reference/android/os/AsyncTask.html –

+0

düzenlemek ur yanıtı AsyncTask'da sınıf bloğunu nereye koymak istediğinizi veya yöntemi, bu sınıfa sorguyu iletmek, bayt [] bildirmek, Birisi için yararlı olacaktır, teşekkür ederiz. –

0

Http İstemcisini Apache Commons'tan kullanabilirsiniz. Örneğin:

private class PostTask extends AsyncTask<String, String, String> { 
     @Override 
     protected String doInBackground(String... data) { 
     // Create a new HttpClient and Post Header 

    HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost("http://<ip address>:3000"); 

     try { 
      //add data 
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); 
      nameValuePairs.add(new BasicNameValuePair("data", data[0])); 
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
      //execute http post 
      HttpResponse response = httpclient.execute(httppost); 

     } catch (ClientProtocolException e) { 

     } catch (IOException e) { 

     } 
     } 
    } 
+0

Android, API 22 seviyesinden beri HttpClient Apache modülünü kullanımdan kaldırmıştır. HttpURLConnection ile gitmelisiniz. –

2
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    new AsyncCaller().execute(); 
} 


private class AsyncCaller extends AsyncTask<Void, Void, Void> 
{ 
    ProgressDialog pdLoading = new ProgressDialog(AsyncExample.this); 

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

     //this method will be running on UI thread 
     pdLoading.setMessage("Loading..."); 
     pdLoading.show(); 
    } 
    @Override 
    protected Void doInBackground(Void... params) { 

     String address = "http://server/postvalue"; 
      JSONObject json = new JSONObject();     
      json.put("username", username); 
      json.put("password", password); 
      String requestBody = json.toString(); 
      URL url = new URL(address); 
      HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 
      urlConnection.setDoOutput(true); 
      urlConnection.setRequestProperty("Content-Type", "application/json"); 
      OutputStream outputStream = new BufferedOutputStream(urlConnection.getOutputStream()); 
      BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8")); 
      writer.write(requestBody); 
      writer.flush(); 
      writer.close(); 
      outputStream.close(); 

      InputStream inputStream; 
      // get stream 
      if (urlConnection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) { 
       inputStream = urlConnection.getInputStream(); 
      } else { 
       inputStream = urlConnection.getErrorStream(); 
      } 
      // parse stream 
      BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); 
      String temp, response = ""; 
      while ((temp = bufferedReader.readLine()) != null) { 
       response += temp; 
      } 

      return response.toString(); 

     } catch (IOException | JSONException e) { 
      return e.toString(); 
     } 

    } 

    @Override 
    protected void onPostExecute(Void result) { 
     super.onPostExecute(result);    
     pdLoading.dismiss(); 
     Log.i(LOG_TAG, "POST\n" + result); 
    } 

    } 
} 
+0

Anahtar değer çiftini geçmek istiyor. Json isteği işe yaramayacak. –

1
DefaultHttpClient httpClient=new DefaultHttpClient(); 
    HttpPost httpPost=new HttpPost(register_user); 
    JSONObject jsonObject=new JSONObject(); 
    httpPost.setHeader("Accept", "application/json"); 
    httpPost.setHeader("Content-type", "application/json"); 
    try { 

     List<NameValuePair> params = new ArrayList<NameValuePair>(); 
     params.add(new BasicNameValuePair("username", username.getText().toString())); 
     params.add(new BasicNameValuePair("password",password.getText().toString())); 
     httpPost.setEntity(new UrlEncodedFormEntity(params)); 


     HttpResponse response=httpClient.execute(httpPost); 


     if(response!=null){ 
      InputStream is=response.getEntity().getContent(); 
      BufferedReader bufferedReader=new BufferedReader(new  InputStreamReader(is)); 
      StringBuilder sb=new StringBuilder(); 
      String line=null; 
      while((line=bufferedReader.readLine())!=null){ 
       sb.append(line+"\n"); 
      } 
      this.message=sb.toString(); 
      //Toast.makeText(getBaseContext(), message, Toast.LENGTH_LONG).show(); 
     } 

    } catch (JSONException e) { 
     e.printStackTrace(); 
    } catch (ClientProtocolException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
İlgili konular