Php 无法向服务器发送GET/POST请求
我正在尝试向服务器发送get数据并读取服务器消息作为响应。后端是PHP,工作正常。但是,每当我试图从android发送数据时,Php 无法向服务器发送GET/POST请求,php,android,Php,Android,我正在尝试向服务器发送get数据并读取服务器消息作为响应。后端是PHP,工作正常。但是,每当我试图从android发送数据时,$\u GET或$\u POST或$\u RESPONSE数组都保持为空 背景是: @Override protected Void doInBackground(Void... params) { Log.d(TAG,"Inside do in background"); try {
$\u GET
或$\u POST
或$\u RESPONSE
数组都保持为空
背景是:
@Override
protected Void doInBackground(Void... params) {
Log.d(TAG,"Inside do in background");
try {
Log.d(TAG,"Here is new url.");
URL url = new URL("http://192.168.1.33/post/home.php");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
//sending data in json format
JSONObject jsonObject = new JSONObject();
jsonObject.put("name","salman Khan");
jsonObject.put("password","khankhan");
String sendingString ;
sendingString = jsonObject.toString();
byte[] outputBytes = sendingString.getBytes("UTF-8");
Log.d(TAG, "Output bytes are " + sendingString);
OutputStream outputStream = urlConnection.getOutputStream();
Log.d(TAG," got output stream.");
outputStream.write(outputBytes);
Log.d(TAG,"I am waiting for response code");
int responseCode = urlConnection.getResponseCode();
Log.d(TAG,"response code: " + responseCode);
if ( responseCode == HttpURLConnection.HTTP_OK)
{
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
Log.d(TAG,"Before reading the line.");
while ( (line = bufferedReader.readLine()) != null )
{
Log.d(TAG, " The line read is: " + line);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
PHP代码:
<?php
$response = array();
// print_r($_GET);
print_r($_REQUEST);
if ( !empty($_GET['name']) || !empty($_GET['password']))
{
// echo "I am in true.";
$response['name'] = $_GET['name'];
$response['password'] = $_GET['password'];
$response['status'] = true;
}
else
{
$response['status'] = false;
}
echo json_encode($response);
?>
检查manifes文件中添加的以下权限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
使用截击,这是传输数据的最佳方式
http://developer.android.com/intl/es/training/volley/index.html
在您的请求类(扩展请求)中,重写getParams()方法。您也可以对标题执行同样的操作,只需覆盖getHeaders()。如果您是通过JSON而不是post字段发送数据,则数据将不在$\u post中。你必须从stdin中读取它。基本上我想发送$\u POST数组。同样的,请指导我。我不懂安卓,所以我不能指导你。但我可以告诉您,看起来您正在以application/json的形式发送数据。如果是这种情况,那么您需要在PHP中正确读取数据,或者以不同的方式发送数据。我已经添加了它。应用程序正在与服务器通信。
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>