gpt4 book ai didi

java - 通过 Android-Java 的 HTTP Post 不起作用

转载 作者:行者123 更新时间:2023-11-30 01:12:01 26 4
gpt4 key购买 nike

我正在使用以下代码将值变量发布到服务器:

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 也正常工作 - 双重检查)。

这可能是什么问题?

最佳答案

我建议改用 volley,这里有一个简单易用的教程: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();
}
}
}

关于java - 通过 Android-Java 的 HTTP Post 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38317614/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com