Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
Solicitud POST de Android con JSON

Después de investigaciones, todavía no puedo enviar una solicitud JSON POST a un servidor.

Ya probé algunas respuestas anteriores:

Java: envío de parámetros HTTP a través del método POST fácilmente

[Android]-POST Json con HttpUrlConnection

Publicar solicitud para registrar datos de usuario en el servidor por HttpUrlConnection

Enviar objeto json a través del método de publicación http en android

¿Cómo enviar un objeto JSON a través de Solicitud con Android?

Mi código actual es:

 FloatingActionButton btn_sendMsg = (FloatingActionButton) findViewById(R.id.btn_sendMsg); btn_sendMsg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { /*Snackbar.make(view, "Sendevorgang...", Snackbar.LENGTH_LONG) .setAction("Action", null).show();*/ createMsg(); } }); private void createMsg() { Message message = new Message(txtbox_msg.getText().toString(), "testUser"); AsyncT asyncT = new AsyncT(); asyncT.execute(message); }

AsyncT.java:

 @Override protected Message doInBackground(Message... params) { try { URL url = new URL("http://[ip]:[port]"); //in the real code, there is an ip and a port HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Accept","application/json"); conn.setDoOutput(true); conn.setDoInput(true); conn.connect(); JSONObject jsonParam = new JSONObject(); jsonParam.put("uname", params[0].getUser()); jsonParam.put("message", params[0].getMessage()); jsonParam.put("latitude", "0"); jsonParam.put("longitude", "0"); jsonParam.put("id", "1"); DataOutputStream os = new DataOutputStream(conn.getOutputStream()); os.writeBytes(URLEncoder.encode(jsonParam.toString(), "UTF-8")); os.flush(); os.close(); Log.i("STATUS", String.valueOf(conn.getResponseCode())); Log.i("MSG" , conn.getResponseMessage()); conn.disconnect(); } catch (Exception e) { } return null; }

Recibo el código de error networkonmainthreadexception 500

Como puedo resolver esto?

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Resuelto:

cambió

 os.writeBytes(URLEncoder.encode(jsonParam.toString(), "UTF-8"));

a

 os.writeBytes(jsonParam.toString());

Y poner el código en un hilo (gracias a @Ravi Sanker)

Código de trabajo:

 public void sendPost() { Thread thread = new Thread(new Runnable() { @Override public void run() { try { URL url = new URL(urlAdress); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); conn.setRequestProperty("Accept","application/json"); conn.setDoOutput(true); conn.setDoInput(true); JSONObject jsonParam = new JSONObject(); jsonParam.put("timestamp", 1488873360); jsonParam.put("uname", message.getUser()); jsonParam.put("message", message.getMessage()); jsonParam.put("latitude", 0D); jsonParam.put("longitude", 0D); Log.i("JSON", jsonParam.toString()); DataOutputStream os = new DataOutputStream(conn.getOutputStream()); //os.writeBytes(URLEncoder.encode(jsonParam.toString(), "UTF-8")); os.writeBytes(jsonParam.toString()); os.flush(); os.close(); Log.i("STATUS", String.valueOf(conn.getResponseCode())); Log.i("MSG" , conn.getResponseMessage()); conn.disconnect(); } catch (Exception e) { e.printStackTrace(); } } }); thread.start(); }
about 4 years ago · Santiago Trujillo Report

0

¿Puedes intentar escribir esto en el método createMsg()?

 Thread thread = new Thread(new Runnable() { @Override public void run() { try { // The code written in doInBackground() } catch (Exception e) { e.printStackTrace(); } }}); thread.start();

La excepción networkonmainthread se produce cuando ejecuta las operaciones de red en el mismo subproceso. Pero, dado que está utilizando una tarea asíncrona, debería funcionar bien. Pero, solo para confirmar.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!