[英][Android]: How can I communicate with php server using httpUrlconnection post with data in outputStream and ensure that server gets in $_POST?
我正在使用HttpURLConnection将json查询传递给php服务器,但它不符合我想要的方式。
连接很好,我从服务器端收到了正确的错误响应,并且我确定json字符串已正确处理。 例如: {"id":55,"date":"2011111","text":"","latitude":13.0,"longitude":123.0,"share":0,"image":"Image","sound":"sound"}
但是,PHP服务器无法使用我发送的字符串加载变量$ _POST。 android端的代码很简单:
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服务器上的代码如下:
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在这种情况下为空,无论我发送了什么..
在重新确定了一点之后,我找到了一个解决方案,必须修改服务器端的代码,如下所示:
$json = file_get_contents('php://input');
$request = json_decode($json, true);
if (isset($request['id'])) {
$id = $request['id'];
无需触摸android代码,服务器即可接收并处理我现在发送的json数据。
问题是没有办法我可以在实际服务器上修改代码。
您以json格式发送数据,但没有以$ _POST数组发送数据,这就是$ _POST为空的原因。 如果您不能更改服务器端代码,则可以尝试使用HttpConnection类。 希望这会起作用。
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发送数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.