2015-12-28 2 views
-3

Я новичок в Andorid и понимаю, что следующий метод отправки почтовых запросов устарел в Android 22 и более поздних версиях. Будет ли у кого-нибудь рабочий образец Android-кода, используя метод URLCONNECTION, упорядочивающий запрос JSON POST (я предполагаю, что это базовая модель, не использующая импорт org.apache.http.client).Отправка запроса JSON POST на Android

package com.hmkcode.android; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import org.apache.http.HttpResponse; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.entity.StringEntity; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.json.JSONObject; 
import android.net.ConnectivityManager; 
import android.net.NetworkInfo; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.TextView; 
import android.widget.Toast; 
import android.app.Activity; 
import com.hmkcode.android.vo.Person; 

public class MainActivity extends Activity implements OnClickListener { 

    TextView tvIsConnected; 
    EditText etName,etCountry,etTwitter; 
    Button btnPost; 

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

     // get reference to the views 
     tvIsConnected = (TextView) findViewById(R.id.tvIsConnected); 
     etName = (EditText) findViewById(R.id.etName); 
     etCountry = (EditText) findViewById(R.id.etCountry); 
     etTwitter = (EditText) findViewById(R.id.etTwitter); 
     btnPost = (Button) findViewById(R.id.btnPost); 

     // check if you are connected or not 
     if(isConnected()){ 
      tvIsConnected.setBackgroundColor(0xFF00CC00); 
      tvIsConnected.setText("You are conncted"); 
     } 
     else{ 
      tvIsConnected.setText("You are NOT conncted"); 
     } 

     // add click listener to Button "POST" 
     btnPost.setOnClickListener(this); 

    } 

    public static String POST(String url, Person person){ 
     InputStream inputStream = null; 
     String result = ""; 
     try { 

      // 1. create HttpClient 
      HttpClient httpclient = new DefaultHttpClient(); 

      // 2. make POST request to the given URL 
      HttpPost httpPost = new HttpPost(url); 

      String json = ""; 

      // 3. build jsonObject 
      JSONObject jsonObject = new JSONObject(); 
      jsonObject.accumulate("name", person.getName()); 
      jsonObject.accumulate("country", person.getCountry()); 
      jsonObject.accumulate("twitter", person.getTwitter()); 

      // 4. convert JSONObject to JSON to String 
      json = jsonObject.toString(); 

      // ** Alternative way to convert Person object to JSON string usin Jackson Lib 
      // ObjectMapper mapper = new ObjectMapper(); 
      // json = mapper.writeValueAsString(person); 

      // 5. set json to StringEntity 
      StringEntity se = new StringEntity(json); 

      // 6. set httpPost Entity 
      httpPost.setEntity(se); 

      // 7. Set some headers to inform server about the type of the content 
      httpPost.setHeader("Accept", "application/json"); 
      httpPost.setHeader("Content-type", "application/json"); 

      // 8. Execute POST request to the given URL 
      HttpResponse httpResponse = httpclient.execute(httpPost); 

      // 9. receive response as inputStream 
      inputStream = httpResponse.getEntity().getContent(); 

      // 10. convert inputstream to string 
      if(inputStream != null) 
       result = convertInputStreamToString(inputStream); 
      else 
       result = "Did not work!"; 

     } catch (Exception e) { 
      Log.d("InputStream", e.getLocalizedMessage()); 
     } 

     // 11. return result 
     return result; 
    } 

    public boolean isConnected(){ 
     ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE); 
      NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); 
      if (networkInfo != null && networkInfo.isConnected()) 
       return true; 
      else 
       return false;  
    } 
    @Override 
    public void onClick(View view) { 

     switch(view.getId()){ 
      case R.id.btnPost: 
       if(!validate()) 
        Toast.makeText(getBaseContext(), "Enter some data!", Toast.LENGTH_LONG).show(); 
       // call AsynTask to perform network operation on separate thread 
       new HttpAsyncTask().execute("http://hmkcode.appspot.com/jsonservlet"); 
      break; 
     } 

    } 
    private class HttpAsyncTask extends AsyncTask<String, Void, String> { 
     @Override 
     protected String doInBackground(String... urls) { 

      person = new Person(); 
      person.setName(etName.getText().toString()); 
      person.setCountry(etCountry.getText().toString()); 
      person.setTwitter(etTwitter.getText().toString()); 

      return POST(urls[0],person); 
     } 
     // onPostExecute displays the results of the AsyncTask. 
     @Override 
     protected void onPostExecute(String result) { 
      Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show(); 
     } 
    } 

    private boolean validate(){ 
     if(etName.getText().toString().trim().equals("")) 
      return false; 
     else if(etCountry.getText().toString().trim().equals("")) 
      return false; 
     else if(etTwitter.getText().toString().trim().equals("")) 
      return false; 
     else 
      return true;  
    } 
    private static String convertInputStreamToString(InputStream inputStream) throws IOException{ 
     BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); 
     String line = ""; 
     String result = ""; 
     while((line = bufferedReader.readLine()) != null) 
      result += line; 

     inputStream.close(); 
     return result; 

    } 
} 
+0

спросите лучше, если вы хотите получить дополнительные вещи в ответ – Badulake

ответ

-1

Здесь у вас есть:

URL url = new URL("http://yoururl.com"); 
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); 
conn.setReadTimeout(10000); 
conn.setConnectTimeout(15000); 
conn.setRequestMethod("POST"); 
conn.setDoInput(true); 
conn.setDoOutput(true); 

List<NameValuePair> params = new ArrayList<NameValuePair>(); 
params.add(new BasicNameValuePair("firstParam", paramValue1)); 
params.add(new BasicNameValuePair("secondParam", paramValue2)); 
params.add(new BasicNameValuePair("thirdParam", paramValue3)); 

OutputStream os = conn.getOutputStream(); 
BufferedWriter writer = new BufferedWriter(
     new OutputStreamWriter(os, "UTF-8")); 
writer.write(getQuery(params)); 
writer.flush(); 
writer.close(); 
os.close(); 

conn.connect(); 
+0

Зачем вы меняете свой ответ ??? !! – Badulake

-1

Действительно, httpClient устарел.

Вы должны обновить HttpURLConnection или даже лучше HttpsURLConnection:

public static String httpPost(String urlString, HashMap<String, String> postDataParams) { 
    URL url; 
    String response = ""; 
    try { 
     url = new URL(urlString); 

     HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); 
     conn.setRequestMethod("POST"); 
     conn.setDoInput(true); 
     conn.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(); 

     if (responseCode == HttpsURLConnection.HTTP_OK) { 
      String line; 
      BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
      while ((line = br.readLine()) != null) { 
       response += line; 
      } 
     } else { 
      response = ""; 
      //throw new HttpException(responseCode+""); 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    if (BuildConfig.DEBUG) { 
     Log.d(LOG_TAG, "response = " + response); 
    } 


    return response; 
} 

public static String getPostDataString(HashMap<String, String> params) { 
    StringBuilder result = new StringBuilder(); 

    try { 
     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")); 
     } 
    } catch (UnsupportedEncodingException e) { 
     e.printStackTrace(); 
    } 

    return result.toString(); 
} 

DOWNLOAD SAMPLE

+0

у вас будет полный образец, запускаемый в Android Studio? – Amir

+0

Я загрузил образец на megaupload. разве вы не просите? – meda

+0

amir не заслуживает доступа к stackoverflow. Он просил что-то, но он уменьшает число людей, которые пытаются ему помочь ... – Badulake

0

своего время использовать залп братан, андроид сети библиотека это быстро и намного лучше, чем запрос HTTP в исполнении , несколько особенностей залпа.

  1. Запрос очередь и приоритезации
  2. Эффективные кэш запроса и управление памятью
  3. расширяемость и настройка библиотеки для наших нужд
  4. Отмены запросы

здесь и может делать то же самое с волейболом прежде всего установить зависимости

compile 'com.mcxiaoke.volley:library-aar:1.0.0' 

после этого создать одноэлементный класс

import com.volley.examples; 
import android.app.Application; 
import android.text.TextUtils; 

import com.android.volley.Request; 
import com.android.volley.RequestQueue; 
import com.android.volley.toolbox.ImageLoader; 
import com.android.volley.toolbox.Volley; 

public class AppController extends Application { 

    public static final String TAG = AppController.class 
      .getSimpleName(); 

    private RequestQueue mRequestQueue; 
    private ImageLoader mImageLoader; 

    private static AppController mInstance; 

    @Override 
    public void onCreate() { 
     super.onCreate(); 
     mInstance = this; 
    } 

    public static synchronized AppController getInstance() { 
     return mInstance; 
    } 

    public RequestQueue getRequestQueue() { 
     if (mRequestQueue == null) { 
      mRequestQueue = Volley.newRequestQueue(getApplicationContext()); 
     } 

     return mRequestQueue; 
    } 

    public ImageLoader getImageLoader() { 
     getRequestQueue(); 
     if (mImageLoader == null) { 
      mImageLoader = new ImageLoader(this.mRequestQueue, 
        new LruBitmapCache()); 
     } 
     return this.mImageLoader; 
    } 

    public <T> void addToRequestQueue(Request<T> req, String tag) { 
     // set the default tag if tag is empty 
     req.setTag(TextUtils.isEmpty(tag) ? TAG : tag); 
     getRequestQueue().add(req); 
    } 

    public <T> void addToRequestQueue(Request<T> req) { 
     req.setTag(TAG); 
     getRequestQueue().add(req); 
    } 

    public void cancelPendingRequests(Object tag) { 
     if (mRequestQueue != null) { 
      mRequestQueue.cancelAll(tag); 
     } 
    } 
} 

это как это просто скопировать и вставить и назовите его AppController затем сделать несколько изменений в манифесте добавить его в приложение тег манифеста

андроид: имя = "com.volley.examples.AppController"

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.volley.examples" 
    android:versionCode="1" 
    android:versionName="1.0" > 

    <uses-sdk 
     android:minSdkVersion="8" 
     android:targetSdkVersion="19" /> 

    <uses-permission android:name="android.permission.INTERNET" /> 

    <application 
     android:name="com.volley.examples.AppController" 
     android:allowBackup="true" 
     android:icon="@drawable/ic_launcher" 
     android:label="@string/app_name" 
     android:theme="@style/AppTheme" > 
     <!-- all activities and other stuff --> 
    </application> 

</manifest> 

и, наконец, последний, чтобы сделать запрос json и вот как вы можете это сделать.

// Tag used to cancel the request 

    String tag_json_obj = "json_obj_req"; 
    //change the url with your's 
    String url = "http://www.exampleUrl.com/androidVersion.json"; 

    ProgressDialog pDialog = new ProgressDialog(this); 
    pDialog.setMessage("Loading..."); 
    pDialog.show();  

      JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST, 
        url, null, 
        new Response.Listener<JSONObject>() { 

         @Override 
         public void onResponse(JSONObject response) { 
          Log.d(TAG, response.toString()); 
          pDialog.hide(); 
         } 
        }, new Response.ErrorListener() { 

         @Override 
         public void onErrorResponse(VolleyError error) { 
          VolleyLog.d(TAG, "Error: " + error.getMessage()); 
          pDialog.hide(); 
         } 
        }) { 

       @Override 
       protected Map<String, String> getParams() { 
        Map<String, String> params = new HashMap<String, String>(); 
        params.put("name", "Android Volley"); 
        params.put("email", "[email protected]"); 
        params.put("password", "password123"); 

        return params; 
       } 

      }; 

    // Adding request to request queue 
    AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj); 

и залпа вы можете сделать практически любой тип запроса путем расширения класса залпа но по умолчанию мы имеем

1.StringRequest 2. JsonObjectRequest 3.JsonArrayRequest

и выше мы использовали JsonObjectRequest

Я знаю, что это не является прямым ответом на ваш вопрос, но я надеюсь, что это поможет вам некоторые, как мало или больше.

спасибо.

+0

Проблема с этими библиотеками заключается в том, что они не поддерживаются позже. – Amir

Смежные вопросы