필자는 안드로이드 앱으로 필사적으로 문제를 해결하려고합니다. 열거 형을 '태그'로 설정하여 내 서버에 목록을 제출합니다. PHP 페이지는이 태그를보고 관련 함수를 수행하고 json 배열 또는 객체로 리턴해야합니다. 이 응용 프로그램의 한 버전과 잘 작동하지만 복제 된 버전은 데이터를 가져 오지 못합니다. PHP는 그냥 isset 태그에서 태그 검사를 넘어서 점프하고 태그는 빈 상태가 아니므로 빈 POST를 보아서 평평해야합니다. 그렇지 않으면 제출 한 객체가 내가 알지 못하는 일부 요구 사항을 충족시키지 못합니다.
많은 게시물을 살펴본 결과 검색 및 검색했지만 해결책을 찾지 못했습니다. 한 버전의 앱에서는 작동하지만 업그레이드 된 버전에서는 작동하지 않고 데이터를 전송하는 데 사용 된 메소드를 변경하지 않은 이유는 무엇입니까 ??
그래서 여기에 대해 다루고 있습니다. 시작하기 위해, AsyncTask를이 객체를 받아 처리하는 클래스에 전달 통신 :
public class CloudConnect {
private String site;
private InputStream is;
private Gson gson;
public CloudConnect(String site) throws MalformedURLException {
this.site = site;
this.gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
is = null;
}
public synchronized Message get(Message m) throws IOException {
Message msg = null;
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(this.site);
post.setEntity(new UrlEncodedFormEntity(validateMessage(m)));
HttpResponse response = client.execute(post);
StatusLine status = response.getStatusLine();
if (status.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
is = entity.getContent();
try {
Reader read = new InputStreamReader(is);
String str = (String) gson.fromJson(read, Object.class);
JsonParser parser = new JsonParser();
JsonElement jElem = parser.parse(str);
JsonObject jObject = (JsonObject) jElem;
msg = gson.fromJson(jObject, Message.class);
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return msg;
}
public synchronized List<Message> getAll(Message m) throws IOException {
List<Message> mList = new ArrayList<Message>();
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(this.site);
post.setEntity(new UrlEncodedFormEntity(validateMessage(m)));
HttpResponse response = client.execute(post);
StatusLine status = response.getStatusLine();
if (status.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
is = entity.getContent();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
JsonArray jArray = null;
JsonReader jReader = new JsonReader(reader);
jReader.setLenient(true);
JsonParser parser = new JsonParser();
if (parser.parse(jReader).isJsonArray()){
jArray = parser.parse(jReader).getAsJsonArray();
if (m instanceof User){
for (JsonElement je : jArray) {
mList.add(gson.fromJson(je, Job.class));
Log.d("json", je.toString());
}
} else if (m instanceof Job) {
for (JsonElement je : jArray) {
mList.add(gson.fromJson(je, Update.class));
Log.d("json", je.toString());
}
}
} else {
JsonElement jElem = parser.parse(jReader);
JsonObject jObject = (JsonObject) jElem;
Error msg = null;
msg = gson.fromJson(jObject, Error.class);
mList.add(msg);
}
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return mList;
}
그리고 PHP : 단일 JSON 객체 또는 객체의 배열을 얻을 수있는 CloudConnect 클래스를 사용
private class UpdateJobList extends AsyncTask<User, Void, Boolean> {
private List<Message> messages;
public UpdateJobList() {
super();
messages = new ArrayList<Message>();
}
@Override
protected Boolean doInBackground(User... params){
try {
CloudConnect cConn = new CloudConnect(sAddress);
this.messages = cConn.getAll(params[0]);
return true;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
@Override
protected void onPostExecute(Boolean result) {
if (true)
{
handleMessageList(messages);
}
}
}
태그를 확인하는 코드 :
if (isset($_POST['messageType']) && $_POST['messageType'] != "") {
$tag = $_POST['messageType'];
//
//various functions depending on messageType tag here. Such as getUser($email).
//functions appear to work fine if the PHP doesn't find the initial conditions
//false and skips them all.
} else {
$response["success"] = 0;
$response["error"]["errorMsg"] = "Tags are null";
$response["error"]["messageType"] = $tag;
$response["error"]["varDump"] = var_dump($_POST);
echo json_encode($response);
}
문제점을 이해할 수 없습니다. 당신은 더 구체적 일 수 있습니까? –
그래. 미안해. 내 애플 리케이션 서버에서 json 개체에 대한 HttpPost 요청을 보냅니다. (App -> PHP -> SQL -> PHP -> JSON 인 코드 -> App) Eclipse에서 Log를 사용하여 EntityUtils.toString (post.getEntity())을 사용하여 객체 값을 표시하여 전송 된 메시지가 null이 아닌지 확인할 수 있습니다.). 그러나 서버의 응답은 항상 전송 된 태그가 null 인 오류입니다. PHP는 시작시 태그가 null 또는 비어 있지 않은지 확인하여 함수를 수행 할 수 있도록합니다. 그러나 HttpPost의 객체가 유효 함에도 불구하고 항상 빈 태그 또는 null 태그가 표시됩니다. – fakataha