1

I can't send post request to the server from my Android app. I have found some examples about how to send POST but I have some error with my code and here is the code:

public class MainActivity extends Activity { private WebView wv; //Internet private EditText email1; //Edit's private EditText email2; //Edit's private Button btn_get_access; //Get Access private String post_url = "http://rasnacis.lv/vova.php"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); wv = (WebView) findViewById(R.id.webView1); email1 = (EditText) findViewById(R.id.txt_email_1); email2 = (EditText) findViewById(R.id.txt_email_2); btn_get_access = (Button) findViewById(R.id.btn_get_access); WebSettings webSettings = wv.getSettings(); webSettings.setSaveFormData(true); //BUTTON OnClickListener ocl_btn_get_access = new OnClickListener() { public void onClick(View v) { String givenEmail1 = email1.getEditableText().toString(); String givenEmail2 = email2.getEditableText().toString(); //SENDING POST if (givenEmail1.length() > 0 && givenEmail2.length() > 0) { HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(post_url); try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("email1", "email2")); nameValuePairs.add(new BasicNameValuePair("email1", "slgjlskjgsg")); nameValuePairs.add(new BasicNameValuePair("email2", "xkjfhgkdjfhgkdjfg")); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httpClient.execute(httpPost); } catch (ClientProtocolException e) { System.out.println("First Exception caz of HttpResponese :" + e); e.printStackTrace(); } catch (IOException e) { System.out.println("Second Exception caz of HttpResponse :" + e); e.printStackTrace(); } } else { Toast.makeText(getBaseContext(), "All fields are required!", Toast.LENGTH_SHORT).show(); } //sending GET //wv.loadUrl("http://rasnacis.lv/vova.php?email1=" + email1.getText() + "&email2=" + email2.getText()); } }; btn_get_access.setOnClickListener(ocl_btn_get_access); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } } 

so can somebody help me with it? i am just started Android development and don't know many tricks or something difficult...

1
  • 1
    Have you checked <uses-permission android:name="android.permission.INTERNET"></uses-permission> ? Commented Feb 26, 2013 at 6:19

2 Answers 2

13

i have use this technique to knock server using post method:

new Thread( new Runnable() { @Override public void run() { try { query = "name="+username+"&pass="+passwaord; URL url = new URL("https:www.example.com/login.php"); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setRequestProperty("Cookie", cookie); //Set to POST connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setReadTimeout(10000); Writer writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(query); writer.flush(); writer.close(); } catch (Exception e) { // TODO Auto-generated catch block Log.e(Tag, e.toString()); } } }).start(); 

i hope it will help. be sure that, cookie is need or not to post for your purpose. if not then u can ignore connection.setRequestProperty("Cookie", cookie); line.

query can be created by BasicNameValuePair, but the proccess i have used is lot more easier to me.

make sure u have set the permission in your manifest for internet:

<uses-permission android:name="android.permission.INTERNET" /> 
Sign up to request clarification or add additional context in comments.

5 Comments

I think this is a better answer, making the POST on a runnable thread will prevent getting a NetworkOnMainThreadException. Thanks!
Also the Apache libraries have been removed in Android Marshmallow so this is now the only viable option.
where is the result?
how to get response of the post request?
@AsadullahAli: I have not coded on android for a very long time. but, i think you can get the response from connection.getInputStream().
4

This is the doPostRequest() method to use in your application,

that is useful for you and perfectly working in my code...

private void doPostRequest(){ String urlString = "http://rasnacis.lv/vova.php"; try { HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(urlString); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("email1_tag", new StringBody("email1_put_here")); reqEntity.addPart("email2_tag", new StringBody("email2_put)here")); reqEntity.addPart("email3_tag", new StringBody("email3_put_here")); post.setEntity(reqEntity); HttpResponse response = client.execute(post); resEntity = response.getEntity(); final String response_str = EntityUtils.toString(resEntity); if (resEntity != null) { Log.i("RESPONSE",response_str); runOnUiThread(new Runnable(){ public void run() { try { } catch (Exception e) { e.printStackTrace(); } } }); } } catch (Exception ex){ Log.e("Debug", "error: " + ex.getMessage(), ex); } } 

If you Implement this code you required two library files:

http://repo1.maven.org/maven2/org/apache/httpcomponents/httpmime/4.0.1/httpmime-4.0.1.jar

http://repo1.maven.org/maven2/org/apache/james/apache-mime4j/0.6/apache-mime4j-0.6.jar

6 Comments

can you please tell me, what i need to include into project for MultipartEntity, StringBody and resEntity, because now i have an error on this..
@vladimir Actualy you don't need MultipartEntity always. Use HttpEntity it will do for you
@pKs ok, but what about resEntity... what type or object is it?
emmm, i have some question about this code, because in my case programm hangs on string MultipartEntity reqEntity = new MultipartEntity(); and nothing happens next..
+1 HttpPost is deprecated since android api level 21
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.