2012-04-30 117 views
1

我想构建一个小应用程序,其中应用程序将与JSON对象的帮助下与PHP脚本进行通信。我成功实现了GET请求测试应用程序,但是对帖子使用JSON会产生问题。该代码不会产生错误,但用什么都没有,除了一个空的Array(我的PHP脚本回复)这意味着什么用的代码连接发送:如何通过POST请求与Android发送JSON对象

<?php print_r($_REQUEST); ?> 

<?php print($_REQUEST['json']); ?> 

抛出HTML努力回到带有json变量未找到错误的应用程序。

我已经试过这里提到的几个解决方案,包括:How to send a JSON object over Request with Android?How to send a json object over httpclient request with android所以如果你能指出我的错误并能简要描述我到底做错了什么,那将是非常好的。谢谢。

下面是JSON对象从哪里转换为字符串,然后附加到Post变量的代码片段。

 DefaultHttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppostreq = new HttpPost(wurl); 
     StringEntity se = new StringEntity(jsonobj.toString()); 
     se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); 
     httppostreq.setEntity(se); 
      //httppostreq.setHeader("Accept", "application/json"); 
     //httppostreq.setHeader("Content-type", "application/json"); 
     //httppostreq.setHeader("User-Agent", "android"); 
     HttpResponse httpresponse = httpclient.execute(httppostreq); 
     HttpEntity resultentity = httpresponse.getEntity(); 

这里是Wireshark的,通过收集,如果它可以帮助TCP流转储:

POST /testmysql.php?test=true HTTP/1.1 
Content-Length: 130 
Content-Type: application/json;charset=UTF-8 
Content-Type: application/json;charset=UTF-8 
Host: 192.168.100.4 
Connection: Keep-Alive 
User-Agent: Apache-HttpClient/UNAVAILABLE (java 1.4) 
{"weburl":"hashincludetechnology.com","header":{"devicemodel":"GT-I9100","deviceVersion":"2.3.6","language":"eng"},"key":"value"}HTTP/1.1 200 OK 
Date: Mon, 30 Apr 2012 22:43:10 GMT 
Server: Apache/2.2.17 (Win32) 
Content-Length: 34 
Keep-Alive: timeout=5, max=100 
Connection: Keep-Alive 
Content-Type: text/html 
Array 
(
    [test] => true 
) 
Test // echo statement left intentionally. 
+0

您是否尝试过使用数据包嗅探器来确定问题出在客户端还是服务器端? – Steve

+0

@Steve脚本实际上是使用Array()发回数据包,并且如果我在URL的追加GET请求的地方,那么这些变量在请求数组中也会返回。只有这个JSON对象会造成问题。 我在我的i9100上通过局域网测试这个应用程序到我的安装了wamp(Apache服务器)的系统上,并且所有其他项目都正常工作 –

回答

1
您使用在服务器端PHP

,所以你的HTTP实体必须是一个多编码的一个。请参阅this link。您正在使用字符串实体,但这不正确。它必须是MultipartEntity,它模拟浏览器在网页中提交表单时的功能。 MultipartEntity应该在httpmime jar中。

一旦你有你的多部分实体,只需添加一个名为“json”的零件,并将其内容设置为你的json编码对象的字符串表示。

请注意,这个答案是因为您在服务器端使用PHP,所以您必须使用其“协议”通过$ _REQUEST读取变量。如果你在服务器端使用你自己的请求解析器,即使是一个StringEntity也可以。请参见HTTP_RAW_POST_DATA

+0

如果您可以提供示例吗? 我需要在MultipartEntity中嵌入JSON对象吗? 任何帮助将是伟大的。 –

+0

我更新了我的答案。无论如何,你应该创建一个多部分实体并添加一个名为“json”的部分,其中包含来自json的内容。toString() – Raffaele

+0

$ HTTP_RAW_POST_DATA像魔术一样工作,我更愿意围绕原始发布数据构建自己的解析器。非常感谢。 –

1

下面应该可以工作。确保为您的表单帖子期望的顶部设置适当的键。此外,我还包括如何发送图像以及其他各种json数据,如果没有必要删除这些行。

static private String postToServerHelper(
      String action, 
      JSONObject jsonData, 
      byte[] imageData){ 

     // keys for sending to server 
     /** The key for the data to post to server */ 
     final String KEY_DATA = "data"; 
     /** The key for the action to take on server */ 
     final String KEY_ACTION = "action"; 
     /** The return code for a successful sync with server */ 
     final int GOOD_RETURN_CODE = 200; 
     /** The key for posting the image data */ 
     final String KEY_IMAGE = "imageData"; 
     /** The image type */ 
     final String FILE_TYPE = "image/jpeg"; 
     /** The encoding type of form data */ 
     final Charset ENCODING_TYPE = Charset.forName("UTF-8"); 

     // the file "name" 
     String fileName = "yourFileNameHere"; 

     // initialize result string 
     String result = ""; 

     // initialize http client and post to correct page 
     HttpClient client = new DefaultHttpClient(); 
     HttpPost httpPost = new HttpPost("http://www.yourdomain.com/yourpage.php"); 

     // set to not open tcp connection 
     httpPost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false); 

     // build the values to post, the action and the form data, and file data (if any) 
     MultipartEntity multipartEntity = new MultipartEntity(
       HttpMultipartMode.BROWSER_COMPATIBLE); 
     try{ 
      multipartEntity.addPart(KEY_ACTION, new StringBody(action, ENCODING_TYPE)); 
      multipartEntity.addPart(KEY_DATA, new StringBody(jsonData.toString(), ENCODING_TYPE)); 
      if (imageData != null){ 
       multipartEntity.addPart(KEY_IMAGE, new ByteArrayBody(imageData, FILE_TYPE, fileName)); 
      } 
     }catch (Exception e){ 
      return e.getMessage(); 
     } 

     // set the values to the post 
     httpPost.setEntity(multipartEntity); 

     int statusCode= -1; 

     // send post 
     try { 
      // actual send 
      HttpResponse response = client.execute(httpPost); 

      // check what kind of return 
      StatusLine statusLine = response.getStatusLine(); 
      statusCode = statusLine.getStatusCode(); 

      // good return 
      if (statusCode == GOOD_RETURN_CODE) { 
       // read return 
       HttpEntity entity = response.getEntity(); 
       InputStream content = entity.getContent(); 
       BufferedReader reader = new BufferedReader(new InputStreamReader(content)); 
       String line; 
       while ((line = reader.readLine()) != null) { 
         builder.append(line + "\n"); 
       } 
       content.close(); 
       result = builder.toString(); 

       // bad return 
      } else { 
       return String.parse(statusCode); 
      } 

      // different failures 
     } catch (ClientProtocolException e) { 
      return e.getMessage(); 
     } catch (IOException e) { 
      return e.getMessage(); 
     } 

     // return the result 
     return result; 
    } 
+0

Raffaele的答案解决了我的问题,仍然非常感谢您花时间回答了一个代码示例,不幸的是我无法投票,但我仍然很高兴您尝试帮助:) –

0

DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url);

  JSONObject clientList = new JSONObject(); 
      clientList.put("name",""); 
      clientList.put("email",""); 
      clientList.put("status",""); 
      clientList.put("page",""); 



      JSONObject listclient = new JSONObject(); 
      listclient.put("mydetail", clientList); 

    //--List nameValuePairs = new ArrayList(1); 
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
      nameValuePairs.add(new BasicNameValuePair("token", tokenid)); 
      nameValuePairs.add(new BasicNameValuePair("json_data", listclient.toString())); 


      httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
      Log.d("JSON",nameValuePairs.toString()); 

      //-- Storing Response 
      HttpResponse httpResponse = httpClient.execute(httpPost); 
+0

编辑我的答案根据你的要求。 –