我使用以下代码将值变量发布到服务器:
protected String doInBackground(String... params) {
try{
URL url= new URL(params[0]);
HttpURLConnection httpURLConnection= (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter= new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String post_data= URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(params[1], "UTF-8");
post_data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(params[2], "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
}catch (MalformedURLException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
return null;
}
下面是异步任务调用:
BackgroundWorker backgroundWorker= new BackgroundWorker(this);
backgroundWorker.execute("http://...", "somename", "somesurname");
代码运行良好(没有错误),但是我无法在我的数据库中看到任何数据(.php也工作正常 - 双重检查)。
这里可能有什么问题?
我建议改用凌空抽射,这里有一个很好且简单的教程:http://www.itsalif.info/content/android-volley-tutorial-http-get-post-put
但这是我如何使用httpURLConnection的:
public String executePost() {
URL url;
HttpURLConnection connection = null;
try {
//Create connection
url = new URL(/*URL HERE*/);
String urlParameters = "/*THE PARAMS. YOU KNOW THIS ;) */";
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" +
Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while ((line = rd.readLine()) != null) {
response.append(line);
response.append(''r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}