2016-08-19 5 views
0

У меня есть HTTPUrlConnection в моем приложении для Android, чтобы отправлять и получать данные из веб-службы. На данный момент я уже достиг, чтобы получить данные и отобразить их, но теперь мне нужно отправить данные, чтобы добавить их в мою базу данных mysql. Как это можно достичь?Android - HTTPUrlConnection POST данные на сервер

Вот мой код:

public class MainActivity extends AppCompatActivity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     new HTTPAsyncTask().execute("http://192.168.0.16/MyDayFiles/borrar.php"); 
    } 

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

      try { // params comes from the execute() call: params[0] is the url. 
       return HttpGet(urls[0]); 
      } catch (IOException e) { 
       return "Unable to retrieve web page. URL may be invalid."; 
      } 
     } 

     @Override // onPostExecute displays the results of the AsyncTask. 
     protected void onPostExecute(String result) { 
      //SHOW RESPONSE 
     } 
    } 

    private String HttpGet(String myUrl) throws IOException { 
     InputStream inputStream = null; 
     String result = ""; 

     URL url = new URL(myUrl); 
     HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // create HttpURLConnection 
     conn.connect(); // make GET request to the given URL 
     inputStream = conn.getInputStream(); // receive response as inputStream 

     if(inputStream != null) { // convert inputstream to string 
      result = convertInputStreamToString(inputStream); 
     }else { 
      result = "Hubo un error."; 
     } 
     return result; 
    } 

    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

Вы можете добавить следующий метод внутри MainActivity класса:

public String HttpPost(String myUrl, String contentType, byte[] data) throws IOException 
{ 
    URL url = new URL(myURL); 
    HttpUrlConnection urlConnection = (HttpUrlConnection)url.openConnection(); 

    urlConnection.setRequestMethod("POST"); 
    urlConnection.setDoOutput(true); 
    urlConnection.setDoInput(true); 

    //I suggest you to receive an ArrayList of Pair<String, String> or 
    //somethig and then iterate it setting all request header properties that 
    //you need. 
    urlConnection.setRequestProperty("Content-Type", contentType); 

    OutputStream outputStream = urlConnection.getOutputStream(); 
    outputStream.write(data); 

    //You can handle HTTP errors based on this code 
    int responseCode = urlConnection.getResponseCode(); 
    InputStream inputStream = urlConnection.getErrorStream(); 

    if(inputStream == null) //If inputStream is null here, no error has occured. 
     inputStream = urlConnection.getInputStream(); 

    return convertInputStreamToString(inputStream); 
} 

Надеется, что это помогает!

+0

Имейте в виду, значение, которое я вышлю, находится в этой строке? urlConnection.setRequestProperty («Content-Type», contentType); –

+0

'contentType' - это переменная, которую вы получите как параметр в этом методе, например 'application/json'; 'text/html' и т. д. –

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