在Android/Java中使用AsyncTask发出HTTP POST请求时遇到问题
简言之,我面临的问题是双重的;我的请求没有将其数据发布到服务器,并且AsyncTask似乎在每次执行时执行多次。我会详细说明 我正在使用用PHP编写的web服务开发一个应用程序。在我的应用程序代码中,我有触发我的请求处理程序在Android/Java中使用AsyncTask发出HTTP POST请求时遇到问题,java,php,android,android-asynctask,Java,Php,Android,Android Asynctask,简言之,我面临的问题是双重的;我的请求没有将其数据发布到服务器,并且AsyncTask似乎在每次执行时执行多次。我会详细说明 我正在使用用PHP编写的web服务开发一个应用程序。在我的应用程序代码中,我有触发我的请求处理程序newhttprequesthandler()的事件 几乎可以肯定的是,这两行代码之间存在问题: try { json.put("test", uri[1]); Log.d("Testing", uri[1]); StringEntity htt
newhttprequesthandler()的事件代码>
几乎可以肯定的是,这两行代码之间存在问题:
try {
json.put("test", uri[1]);
Log.d("Testing", uri[1]);
StringEntity httpPost = new StringEntity(json.toString(), HTTP.UTF_8);
httpPost.setContentType("application/json");
post.setEntity(httpPost);
httpclient.execute(post);
result = "Success";
} catch (JSONException e) {
//some Error logging(e);
}
它似乎没有向请求附加任何URL参数,因此没有数据被发送到我的服务器。这是我的RequestHandler代码
公共类HTTPRequestHandler扩展异步任务{
final String key = "?key=verylongkey";
@Override
public String doInBackground(String... uri) {
String verb = uri[1];
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
InputStream inputStream = null;
StringBuilder stringbuilder = new StringBuilder();
String result = null;
//begin GET request
if(verb.equals("GET")){
//functional code for get; prints desired results
}
//begin POST request
}else if(verb.equals("POST")){
HttpPost post = new HttpPost(uri[0]+key);
JSONObject json = new JSONObject();
try {
json.put("test", uri[1]);
Log.d("Testing", uri[1]);
StringEntity httpPost = new StringEntity(json.toString(), HTTP.UTF_8);
httpPost.setContentType("application/json");
post.setEntity(httpPost);
httpclient.execute(post);
result = "Success";
} catch (JSONException e) {
Log.e("Testing", "Execution failure: exception: ", e);
} catch (UnsupportedEncodingException e){
Log.e("Testing", "Execution failure: exception: ", e);
} catch (ClientProtocolException e) {
Log.e("Testing", "Execution failure: exception: ", e);
} catch (IOException e) {
Log.e("Testing", "Execution failure: exception: ", e);
}
//endregion
}else{
result = "no valid method specified";
}
return result;
}
@Override
public void onPostExecute(String result){
super.onPostExecute(result);
JSONObject jsonObject;
try {
jsonObject = new JSONObject(result);
List<String> stuff =new ArrayList<String>();
JSONArray cast = jsonObject.getJSONArray("Results");
for (int i=0;i<cast.length();i++){
JSONObject json_data = cast.getJSONObject(i);
Log.d("Testing", "Array["+i+"]"+json_data.getString("mykey"));
}
}catch(JSONException e) {
Log.e("Testing", "Execution failure: exception: ", e);
}
}
}
但是我仍然没有收到帖子。按照一位评论员的建议,使用这种形式的代码来获得最终的PHP响应,有什么好方法呢?我发送的Java代码和接收的PHP代码之间的通信有点不匹配。因为我发送的是JSON,所以我必须这样说,并对发布的数据进行解码。这是很简单的需要注意的是,尽管连接可能已打开,但在读取数据之前,POST
将不会完成
PHP
if (file_get_contents('php://input') != false) {
$data = json_decode(file_get_contents('php://input'), true);
$value = $data["test"];
echo $value;
$insert = mysqli_query($con, "INSERT INTO mytable (mycolumn) VALUES ('$value')");
if($insert){
echo "Success";
}
JAVA
JSONObject json = new JSONObject();
json.put("test","65481");
url = new URL (uri[0]+key);
urlConn = url.openConnection();
urlConn.setDoInput(true);
urlConn.setDoOutput(true);
urlConn.setUseCaches(false);
urlConn.connect();
printout = new DataOutputStream(urlConn.getOutputStream());
byte[] data=json.toString().getBytes("UTF-8");
printout.write(data);
input = new DataInputStream(urlConn.getInputStream());
StringBuffer inputLine = new StringBuffer();
String tmp;
//it seems until input.readLine() is called, the POST would not execute
while ((tmp = input.readLine()) != null){
inputLine.append(tmp);
Log.d("Testing","Contents:"+tmp);
}
printout.flush();
printout.close();
result="Post Success";
我很确定你必须阅读服务器的响应才能真正执行请求。有这样的库!我喜欢的是改装!很难说你想在这里做什么。你明白GET和POST之间的区别吗?使用POST不会向url添加参数。要获取POST参数,请使用\POST
而不是\u GET
。最后,看起来您的代码正试图将JSON发送到PHP,这是您的意图吗?看看我的博客帖子,它可能会有所帮助:@Csteele5看看这个发送JSON的方法:这里是在PHP中接收JSON的方法:@Csteele5如果您发送JSON,您不能使用_GET或\u post,您需要使用json解码(文件获取内容('php://input“),对);
看看这个答案:
if (file_get_contents('php://input') != false) {
$data = json_decode(file_get_contents('php://input'), true);
$value = $data["test"];
echo $value;
$insert = mysqli_query($con, "INSERT INTO mytable (mycolumn) VALUES ('$value')");
if($insert){
echo "Success";
}
JSONObject json = new JSONObject();
json.put("test","65481");
url = new URL (uri[0]+key);
urlConn = url.openConnection();
urlConn.setDoInput(true);
urlConn.setDoOutput(true);
urlConn.setUseCaches(false);
urlConn.connect();
printout = new DataOutputStream(urlConn.getOutputStream());
byte[] data=json.toString().getBytes("UTF-8");
printout.write(data);
input = new DataInputStream(urlConn.getInputStream());
StringBuffer inputLine = new StringBuffer();
String tmp;
//it seems until input.readLine() is called, the POST would not execute
while ((tmp = input.readLine()) != null){
inputLine.append(tmp);
Log.d("Testing","Contents:"+tmp);
}
printout.flush();
printout.close();
result="Post Success";