A
A
Andrey Galushko2015-08-27 21:29:45
Java
Andrey Galushko, 2015-08-27 21:29:45

Sending a POST request to a server in ANDROID (using standard methods out of the box)?

I've been breaking my head for 4 days, I'll show my code below:
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
/**
* Created by andrej on 08/23/15.
*/
public class PostTask extends AsyncTask {
public String str;
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... voids) {
try {
BufferedReader reader = null;
URL url = new URL(" 192.168.1.3:8888/1/login.php ");
HttpsURLConnection conct = (HttpsURLConnection) url.openConnection();
conct.setReadTimeout(10000);
conct.setRequestMethod("POST");
conct.setConnectTimeout(15000);
conct.setRequestProperty("Accept-Charset", "UTF-8");
conct.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
conct.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36");
conct.setDoOutput(true);
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("login", "andrey")
.appendQueryParameter("password", "123456");
String query = builder.build().getEncodedQuery();
Log.e("Data to server", query);
DataOutputStream wr = new DataOutputStream(conct.getOutputStream());
wr.writeBytes(query);
wr flush();
wr.close();
connect();
reader= new BufferedReader(new InputStreamReader(conct.getInputStream()));
StringBuilder buf = new StringBuilder();
string line = null;
while ((line=reader.readLine()) != null) {
buf.append(line + "\n");
}
str = (buf.toString());
Log.e("Data to server", str);
}
catch (Exception e){
Log.e("Error in async task", "DuinBackground");
return null;
}
return null;
}
@Override
protected void onPostExecute(Void Void) {
super.onPostExecute(Void);
//Log.e("Execution result",str);
}
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
C
Chvalov, 2015-08-27
@Chvalov

public void postData() {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        // nameValuePairs.add(new BasicNameValuePair("параметр", "значение"));
        nameValuePairs.add(new BasicNameValuePair("id", "12345"));
        nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
}

Answers: 1 and 2

D
Dmitry Bolshakov, 2015-08-28
@enq3

HttpURLConnection

URL url = new URL("http://backend.com/api.php");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
   try {
     urlConnection.setDoOutput(true);
     urlConnection.setChunkedStreamingMode(0);

     OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
     writeStream(out);

     InputStream in = new BufferedInputStream(urlConnection.getInputStream());
     readStream(in);
    finally {
     urlConnection.disconnect();
   }

A
Andrey, 2015-08-28
@kozinakoff

No need for "regular methods out of the box", use OkHttp.
First we form the header: https://github.com/square/okhttp/wiki/Recipes#acce...
Then the POST request itself: https://github.com/square/okhttp/wiki/Recipes#post...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question