简体   繁体   中英

HttpPost from android not working

From android app i want to send some data . This data should be displayed in website. Currently i'm trying in localhost using XAMPP.

Main Activity

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button sendButton  = (Button) findViewById(R.id.sendButton);
    sendButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            new NetworkOperation().execute();
            //Toast.makeText(getBaseContext(), "response", Toast.LENGTH_LONG).show();
        }
    });

}

Another class

public class NetworkOperation extends AsyncTask<String,Void,String>{

@Override
protected String doInBackground(String... arg0) {
    // TODO Auto-generated method stub
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost("http://192.168.0.104/Project/script.php");
    try{
        List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1);
        nameValuePair.add(new BasicNameValuePair("id","somevalue"));
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
        HttpResponse response = httpClient.execute(httpPost);
        Log.d("Http Response:", (response.getEntity()).toString());
    }catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        System.out.println("clientprotocolexception");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        System.out.println("IOexception");
        e.printStackTrace();
    }finally {
        httpClient.getConnectionManager().shutdown();
    }
    return null;
}

Included in Manifest

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

I have php script file as follows

<?php
$error = 'Not received';
$result =  (isset($_POST['id']) ? $_POST['id'] : $error);
echo $result;

?>

You're sending the HTTP POST request, but not processing the data it returns. This would be an example on how to wait for the response from the server side, I've tried to comment the relevant parts so it should be easy to understand.

HttpResponse response = null;

try {
  // Fill in the POST pair you want to sent to the server
  final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
  nameValuePairs.add(new BasicNameValuePair("mykey", "myvalue"));
  httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

  // Send the request
  response = httpclient.execute(httppost);
}
catch (final ClientProtocolException e) { ... }
catch (final IOException e) { ... }

// Now you have to process the response    
InputStream ips;
try {
  ips = response.getEntity().getContent();
  final BufferedReader buf = new BufferedReader(new InputStreamReader(ips, "UTF-8"));

  StringBuilder sb = new StringBuilder();
  String s;
  while (true) {
    s = buf.readLine();
    if ((s == null) || (s.length() == 0))
      break;
    sb.append(s);
  }

  buf.close();
  ips.close();

  Log.d("JSONResponse", "My response from the server is: " + sb.toString());
} 
catch (IllegalStateException e1) { } 
catch (IOException e1) { }

if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
  try { throw new Exception(response.getStatusLine().getReasonPhrase()); } 
  catch (final Exception e) { e.printStackTrace(); }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM