setrequestproperty example ejemplo java android-emulator android-internet

java - example - setrequestproperty android



Http Get using Android HttpURLConnection (6)

Creé con CallBack (delegado) respuesta a la clase Activity.

public class WebService extends AsyncTask<String, Void, String> { private Context mContext; private OnTaskDoneListener onTaskDoneListener; private String urlStr = ""; public WebService(Context context, String url, OnTaskDoneListener onTaskDoneListener) { this.mContext = context; this.urlStr = url; this.onTaskDoneListener = onTaskDoneListener; } @Override protected String doInBackground(String... params) { try { URL mUrl = new URL(urlStr); HttpURLConnection httpConnection = (HttpURLConnection) mUrl.openConnection(); httpConnection.setRequestMethod("GET"); httpConnection.setRequestProperty("Content-length", "0"); httpConnection.setUseCaches(false); httpConnection.setAllowUserInteraction(false); httpConnection.setConnectTimeout(100000); httpConnection.setReadTimeout(100000); httpConnection.connect(); int responseCode = httpConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(httpConnection.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line + "/n"); } br.close(); return sb.toString(); } } catch (IOException e) { e.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } return null; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); if (onTaskDoneListener != null && s != null) { onTaskDoneListener.onTaskDone(s); } else onTaskDoneListener.onError(); } }

dónde

public interface OnTaskDoneListener { void onTaskDone(String responseData); void onError(); }

Puede modificar de acuerdo a sus necesidades. Es para obtener

Soy nuevo en el desarrollo de Java y Android y trato de crear una aplicación simple que debe contactarse con un servidor web y agregar datos a una base de datos usando http get.

Cuando hago la llamada usando el navegador web en mi computadora, funciona bien. Sin embargo, cuando hago la llamada ejecutando la aplicación en el emulador de Android, no se agregan datos.

He agregado permiso de Internet para el manifiesto de la aplicación. Logcat no informa ningún problema.

¿Alguien puede ayudarme a descubrir qué pasa?

Aquí está el código fuente:

package com.example.httptest; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.widget.TextView; public class HttpTestActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView tv = new TextView(this); setContentView(tv); try { URL url = new URL("http://www.mysite.se/index.asp?data=99"); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.disconnect(); tv.setText("Hello!"); } catch (MalformedURLException ex) { Log.e("httptest",Log.getStackTraceString(ex)); } catch (IOException ex) { Log.e("httptest",Log.getStackTraceString(ex)); } } }


Aquí hay una clase AsyncTask completa

public class GetMethodDemo extends AsyncTask<String , Void ,String> { String server_response; @Override protected String doInBackground(String... strings) { URL url; HttpURLConnection urlConnection = null; try { url = new URL(strings[0]); urlConnection = (HttpURLConnection) url.openConnection(); int responseCode = urlConnection.getResponseCode(); if(responseCode == HttpURLConnection.HTTP_OK){ server_response = readStream(urlConnection.getInputStream()); Log.v("CatalogClient", server_response); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); Log.e("Response", "" + server_response); } } // Converting InputStream to String private String readStream(InputStream in) { BufferedReader reader = null; StringBuffer response = new StringBuffer(); try { reader = new BufferedReader(new InputStreamReader(in)); String line = ""; while ((line = reader.readLine()) != null) { response.append(line); } } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } return response.toString(); }

Para llamar a esta clase AsyncTask

new GetMethodDemo().execute("your web-service url");


Intente obtener la secuencia de entrada a partir de esto, luego puede obtener los datos de texto de esa manera: -

URL url; HttpURLConnection urlConnection = null; try { url = new URL("http://www.mysite.se/index.asp?data=99"); urlConnection = (HttpURLConnection) url .openConnection(); InputStream in = urlConnection.getInputStream(); InputStreamReader isw = new InputStreamReader(in); int data = isw.read(); while (data != -1) { char current = (char) data; data = isw.read(); System.out.print(current); } } catch (Exception e) { e.printStackTrace(); } finally { if (urlConnection != null) { urlConnection.disconnect(); } }

Probablemente también pueda usar otros lectores de inputstream, como el lector de buffer.

El problema es que cuando abres la conexión, no "extrae" ningún dato.


Si solo necesita una llamada muy simple, puede usar la URL directamente:

import java.net.URL; new URL("http://wheredatapp.com").openStream();


URL url = nueva URL (" https://www.google.com ");

// si estás usando

URLConnection conn = url.openConnection ();

// cambiarlo a

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


Solución simple y eficiente : use Volley

StringRequest stringRequest = new StringRequest(Request.Method.GET, finalUrl , new Response.Listener<String>() { @Override public void onResponse(String){ try { JSONObject jsonObject = new JSONObject(response); HashMap<String, Object> responseHashMap = new HashMap<>(Utility.toMap(jsonObject)) ; } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.d("api", error.getMessage().toString()); } }); RequestQueue queue = Volley.newRequestQueue(context) ; queue.add(stringRequest) ;