在Android中发送POST数据

我对PHP,JavaScript和许多其他脚本语言有丰富的经验,但是对Java或Android却没有太多的经验。

我正在寻找一种将 数据发送到PHP脚本并显示结果的方法。

回答:

***更新了适用于Android 6.0+的答案。

    public class CallAPI extends AsyncTask<String, String, String> {

public CallAPI(){

//set context variables if required

}

@Override

protected void onPreExecute() {

super.onPreExecute();

}

@Override

protected String doInBackground(String... params) {

String urlString = params[0]; // URL to call

String data = params[1]; //data to post

OutputStream out = null;

try {

URL url = new URL(urlString);

HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

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

BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));

writer.write(data);

writer.flush();

writer.close();

out.close();

urlConnection.connect();

} catch (Exception e) {

System.out.println(e.getMessage());

}

}

}

Apache Commons的Http Client是必经之路。它已经包含在android中。这是一个简单的示例,说明如何使用HTTP Post。

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("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

}

}

以上是 在Android中发送POST数据 的全部内容, 来源链接: utcz.com/qa/434165.html

回到顶部