问题描述
我正在使用HttpURLConnection将json查询传递给php服务器,但它不符合我想要的方式.
I am using HttpURLConnection to pass json query to php server and it doesn't work the way I want.
连接很好,我从服务器端收到了正确的错误响应,并且我确定json字符串已正确处理.例如:{"id":55,"date":"2011111","text":"","latitude":13.0,"longitude":123.0,"share":0,"image":"Image","sound":"sound"}
The connection is fine, I got proper error respond from server side and I am sure the json string is properly handled. eg:{"id":55,"date":"2011111","text":"","latitude":13.0,"longitude":123.0,"share":0,"image":"Image","sound":"sound"}
但是,php服务器无法使用我发送的字符串加载变量$ _POST. android端的代码很简单:
However, the php server cannot load the variable $_POST with the string that I have sent. The code on android side is simple:
String temp_p = gson.toJson(diary);
URL url2 = new URL( "http://localhost:8080/****");
HttpURLConnection connection = (HttpURLConnection)url2.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
//Send request
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream ());
wr.writeBytes(temp_p);
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();
System.out.println("respons:" + response.toString());
php服务器上的代码如下:
The code on php server looks like:
if (isset($_POST['id'])) {
$id = $_POST['id'];
..blablabla..
}
else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing" ;
$response["_POST"] = $_POST ;
echo json_encode($response);
}
在这种情况下,无论我发送的是什么,$ _ POST为null ..
The $_POST is null in this case no matter what I sent ..
在重新确定了一点之后,我找到了一个解决方案,我必须在服务器端修改代码,如下所示:
And after reaserching a bit, I found a solution that I have to modify the code on server side like the following:
$json = file_get_contents('php://input');
$request = json_decode($json, true);
if (isset($request['id'])) {
$id = $request['id'];
在不触摸android代码的情况下,服务器可以接收并处理我现在发送的json数据.
Without touching the android code, the server can recieve and work on json data I sent now.
问题是我无法在实际服务器上修改代码..因此,为什么$ _POST不能得到p
The problem is there is no way I can modify the code on the actual server.. So any idea why the $_POST not getting p
推荐答案
您正在以json 格式发送数据,但不是以$ _POST数组发送的,这就是$ _POST是空的.如果您无法更改服务器端代码,则可以尝试使用 HttpConnection 类.希望这会起作用.
You are sending data in json format, but not in $_POST array that's why $_POST is empty. If you cannot change server side code, then you may try out my HttpConnection class . Hope this will work.
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class HttpConnection {
private HttpURLConnection conn;
public static final int CONNECTION_TIMEOUT = 15 * 1000;
public JSONObject sendRequest(String link, HashMap<String, String> values) {
JSONObject object = null;
try {
URL url = new URL(link);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(CONNECTION_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
if (values != null) {
OutputStream os = conn.getOutputStream();
OutputStreamWriter osWriter = new OutputStreamWriter(os, "UTF-8");
BufferedWriter writer = new BufferedWriter(osWriter);
writer.write(getPostData(values));
writer.flush();
writer.close();
os.close();
}
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream is = conn.getInputStream();
InputStreamReader isReader = new InputStreamReader(is, "UTF-8");
BufferedReader reader = new BufferedReader(isReader);
String result = "";
String line = "";
while ((line = reader.readLine()) != null) {
result += line;
}
if (result.trim().length() > 2) {
object = new JSONObject(result);
}
}
}
catch (MalformedURLException e) {}
catch (IOException e) {}
catch (JSONException e) {}
return object;
}
public String getPostData(HashMap<String, String> values) {
StringBuilder builder = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : values.entrySet()) {
if (first)
first = false;
else
builder.append("&");
try {
builder.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
builder.append("=");
builder.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
catch (UnsupportedEncodingException e) {}
}
return builder.toString();
}
}
通过调用 sendRequest 方法发出发布请求.您只需传递链接,然后使用HashMap发送数据即可.
Make post request by calling sendRequest method.You have to just pass the link, and the data to send with HashMap.
这篇关于[Android]:如何使用httpUrlconnection post和outputStream中的数据与php服务器通信,并确保服务器进入$ _POST?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!