Php 如何使用HttpUrlConnection通过POST传递参数
EDIT:我发现将OutputStreamWriter包装在BufferedWriter中是导致问题的原因,所以去掉了包装器,我的文章就通过了。仍然想知道为什么BufferedWriter是原因。 我提前道歉,因为我刚刚开始自学数据库、应用程序和服务器/数据库之间的通信以及php 提出的其他类似问题没有提供答案 在使用HttpUrlConnection从我的android应用程序到本地托管服务器上的php脚本制作一篇简单的文章时,我很难辨别我缺少了什么。我需要从android应用程序中获取一个用户ID,将其作为参数传递给php脚本,然后在名为users的数据库表中查找该ID。我还希望使用未弃用的方法和类 我已经在android清单中包含了互联网权限。我使用的是XAMPP,我已经验证了我的服务器正在运行,如果我通过web浏览器访问url,我会得到我想要的JSON响应 我唯一的logcat消息是IOException,它发生在写入输出流之后编辑:特定的异常是“意外终止流” 以下是我的AsyncTask类中的代码:Php 如何使用HttpUrlConnection通过POST传递参数,php,android,post,httpurlconnection,Php,Android,Post,Httpurlconnection,EDIT:我发现将OutputStreamWriter包装在BufferedWriter中是导致问题的原因,所以去掉了包装器,我的文章就通过了。仍然想知道为什么BufferedWriter是原因。 我提前道歉,因为我刚刚开始自学数据库、应用程序和服务器/数据库之间的通信以及php 提出的其他类似问题没有提供答案 在使用HttpUrlConnection从我的android应用程序到本地托管服务器上的php脚本制作一篇简单的文章时,我很难辨别我缺少了什么。我需要从android应用程序中获取一个用
protected String doInBackground(String... params) {
String userID = params[0];
Pair<String, String> phpParameter = new Pair<>("userID", userID);
String result = "";
try {
URL url = new URL("url of locally-hosted php script");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// prepare request
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.setFixedLengthStreamingMode(userID.getBytes("UTF-8").length);
// upload request
OutputStream outputStream = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(phpParameter.first + "=" + phpParameter.second);
writer.close();
outputStream.close();
// read response
BufferedReader in = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) { response.append(inputLine); }
in.close();
result = response.toString();
// disconnect
urlConnection.disconnect();
} catch (MalformedURLException e) {
Log.e("Malformed URL Exception", "Malformed URL Exception");
} catch (IOException e) {
Log.e("IOException", "IOException");
}
return result;
}
受保护的字符串doInBackground(字符串…参数){
字符串userID=params[0];
Pair phpParameter=新对(“userID”,userID);
字符串结果=”;
试一试{
URL=新URL(“本地托管php脚本的URL”);
HttpURLConnection urlConnection=(HttpURLConnection)url.openConnection();
//准备请求
urlConnection.setRequestMethod(“POST”);
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.setFixedLengthStreamingMode(userID.getBytes(“UTF-8”).length);
//上传请求
OutputStream OutputStream=urlConnection.getOutputStream();
BufferedWriter=新的BufferedWriter(
新的OutputStreamWriter(outputStream,“UTF-8”);
writer.write(phpParameter.first+“=”+phpParameter.second);
writer.close();
outputStream.close();
//读取响应
BufferedReader in=新的BufferedReader(
新的InputStreamReader(urlConnection.getInputStream());
字符串输入线;
StringBuffer响应=新的StringBuffer();
while((inputLine=in.readLine())!=null){response.append(inputLine);}
in.close();
结果=response.toString();
//断开
urlConnection.disconnect();
}捕获(格式错误){
Log.e(“格式错误的URL异常”、“格式错误的URL异常”);
}捕获(IOE异常){
Log.e(“IOException”、“IOException”);
}
返回结果;
}
这是我在服务器上的php脚本。我还需要一些准备好的语句的帮助,所以不要因为“id=1”而痛骂我:
<?php
mysql_connect("host","username","password");
mysql_select_db("Database");
print($_POST);
$sql = mysql_query("select * from users where id = 1");
while($row = mysql_fetch_assoc($sql))
$output[] = $row;
print(json_encode($output)); // this will print the output in json
mysql_close();
?>
兄弟,使用像这样的自定义库会更简单。请查看您正在尝试执行的代码示例
你问为什么要用它?所有异常和异步任务都在后台处理,从而简化了代码库
AsyncHttpClient client = new AsyncHttpClient();
client.post(YOUR_POST_URL, new AsyncHttpResponseHandler() {
@Override
public void onStart() {
// called before request is started
}
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
// called when response HTTP status is "200 OK"
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
}
@Override
public void onRetry(int retryNo) {
// called when request is retried
}
});
要从android发布,请执行以下操作:
public class HttpURLConnectionHandler
{
protected String urlG = "http://192.168.43.98/yourdirectory/";
public String sendText(String text)
{
try {
URL url = new URL(urlG+"receiveData.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
// para activar el metodo post
conn.setDoOutput(true);
conn.setDoInput(true);
DataOutputStream wr = new DataOutputStream(
conn.getOutputStream());
wr.writeBytes("mydata="+text);
wr.flush();
wr.close();
InputStream is = conn.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){ return "error";}
}
}
php文件:
$x = $_POST['mydata'];
echo $x;
看来我修好了
我变了
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(phpParameter.first + "=" + phpParameter.second);
到
出于某种原因,将输出流写入器包装在缓冲写入器中的行为破坏了它。我不知道为什么
在进行上述更改后,我收到一个错误,表示流需要1个字节,但收到8个字节,因此我只写了userID,这就是我传递给setFixedLengthStreamingMode的内容。
只有logcat消息是IOException,它发生在写入输出流之后。
。那么,您应该准确地发布哪个异常。您使用的Log.e()
是错误的,这就是您无法获得所需信息的原因。它应该类似于Log.e(“MyClassName”,“我对出错原因的描述”,e)
@Dan Getz哇,很抱歉。我把实际的异常传递给日志时完全搞错了。我得到了“意想不到的结局”。包括一个以上的编辑,以反映这一点!我很欣赏使用外部库的建议,它可能更简单,但我对了解我编写的代码的错误以及原因很感兴趣,而不是首先跳到其他地方,因为它可能更简单。回答完这个问题后,我会看一看,我可以比较这两种方法。酷兄弟。我理解并感谢您的回复,但我在问题中提到,我希望使用未被弃用的方法和类。根据Android开发者文档,HttpClient、HttpPost、HttpResponse等在API级别22中被弃用。HttpClient是deprecated@Rene好的,看到了吗
OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8");
writer.write(userID);