2013-03-18 93 views
0

我試圖通信PHP服務器和Android如何使用POST方法從Android獲取Json DATA?

這是我的JAVA文件和PHP

//使用GSON庫數據轉換成JSON。 - >沒關係!

String str = new TOJSON().tojson("testName", "TestPW", "testEmail", 77); 

    USERDATA userdata = gson.fromJson(new HTTPCONNECTION().httpPost("http://testsever.com/test.php", str).toString(), USERDATA.class); 

    textView textView = (TextView)findViewById(R.id.textView1); 
    textView.setText(userdata.getName()); 

//連接PHP服務器

public class HTTPCONNECTION { 


    public String httpPost(String url, String str){ 
     HttpClient client = new DefaultHttpClient(); 
     HttpConnectionParams.setConnectionTimeout(client.getParams(), 30000); 
     HttpResponse response; 


     try { 
      HttpPost httppost = new HttpPost(url); 
      StringEntity entity = new StringEntity(str, "UTF-8"); 
      entity.setContentType("application/json"); 
      httppost.setEntity(entity); 

      HttpResponse httpResponse = client.execute(httppost); 
      HttpEntity httpEntity = httpResponse.getEntity(); 
      Log.v("OWL", EntityUtils.toString(httpEntity)); 

      return EntityUtils.toString(httpEntity); 
     } 

     catch (ClientProtocolException e) { 
      e.printStackTrace(); 
      return null; 
     } 
     catch (IOException e) { 
      e.printStackTrace(); 
      return null; 
     } 
} 

和PHP文件中獲取JSON數據和發送JSON數據來測試

$value = json_decode(stripslashes($_POST), true); 
echo (json_encode($value)); 
+0

問題在哪裏?你有什麼在PHP方面? – 2013-03-18 14:26:29

回答

1

在我的上側的情況下PHP我使用

$_POST = json_decode(file_get_contents("php://input")); 

而在Android上側

StringEntity se = new StringEntity(jsonObject.toString(), 
        HTTP.UTF_8); 
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, 
        "application/json")); 
request.setEntity(se); 

PHP手冊 - Input/Output PHP Streams

的功能完整的源來自Android的

發送POST JSON數據到服務器
public static void restApiJsonPOSTRequest(
      final DefaultHttpClient httpclient, final HttpPost request, 
      final JSONObject jsonObject, final Handler responder, 
      final int responseCode, final int packetSize) { 

     new Thread(new Runnable() { 

      @Override 
      public void run() { 
       try { 
        try { 

         StringEntity se = new StringEntity(jsonObject 
           .toString(), HTTP.UTF_8); 
         se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, 
           "application/json")); 
         request.setEntity(se); 

         HttpResponse response = httpclient.execute(request); 
         HttpEntity entity = response.getEntity(); 
         if (entity != null) { 
          ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
          DataInputStream dis = new DataInputStream(entity 
            .getContent()); 
          byte[] buffer = new byte[packetSize];// In bytes 
          int realyReaded; 
          double contentSize = entity.getContentLength(); 
          double readed = 0L; 
          while ((realyReaded = dis.read(buffer)) > -1) { 
           baos.write(buffer, 0, realyReaded); 
           readed += realyReaded; 
           sendDownloadingMessage(responder, 
             (double) contentSize, readed); 
          } 
          sendCompleteMessage(responder, 
            new InternetResponse(baos, responseCode, 
              request.getURI().toString())); 
         } else { 
          sendErrorMessage(responseCode, responder, 
            new Exception("Null"), request.getURI() 
              .toString()); 
         } 
        } catch (ClientProtocolException e) { 
         sendErrorMessage(responseCode, responder, e, request 
           .getURI().toString()); 
        } catch (IOException e) { 
         sendErrorMessage(responseCode, responder, e, request 
           .getURI().toString()); 
        } finally { 
         httpclient.getConnectionManager().shutdown(); 
        } 
       } catch (NullPointerException ex) { 
        sendErrorMessage(responseCode, responder, ex, request 
          .getURI().toString()); 
       } 
      } 
     }).start(); 
    } 

或不同的方式

public static void postJSONObject(final String url, 
      final Handler responder, final int responseCode, 
      final int packetSize, final JSONObject jsonObject, 
      final URLConnection connection) { 

     new Thread(new Runnable() { 

      @Override 
      public void run() { 
       System.out.println(connection); 
       sendConnectingMessage(responder); 
       PrintWriter writer = null; 
       ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
       try { 

        HttpURLConnection htt = (HttpURLConnection) connection; 
        htt.setRequestMethod("POST"); 
        OutputStream output = connection.getOutputStream(); // exception 
                     // throws 
                     // here 
        writer = new PrintWriter(new OutputStreamWriter(output, 
          "UTF-8"), true); // true = autoFlush, important! 
        String strJson = jsonObject.toString(); 
        output.write(strJson.getBytes("UTF-8")); 
        output.flush(); 
        System.out.println(htt.getResponseCode()); 
        // Read resposne 
        baos = new ByteArrayOutputStream(); 
        DataInputStream dis = new DataInputStream(
          connection.getInputStream()); 
        byte[] buffer = new byte[packetSize];// In bytes 
        int realyReaded; 
        double contentSize = connection.getContentLength(); 
        double readed = 0L; 
        while ((realyReaded = dis.read(buffer)) > -1) { 
         baos.write(buffer, 0, realyReaded); 
         readed += realyReaded; 
         sendDownloadingMessage(responder, (double) contentSize, 
           readed); 
        } 
        sendCompleteMessage(responder, new InternetResponse(baos, 
          responseCode, url)); 
       } catch (Exception e) { 
        sendErrorMessage(responseCode, responder, e, url); 

       } finally { 
        if (writer != null) { 
         writer.close(); 
        } 
       } 

      } 
     }).start(); 
    } 
+0

感謝您的建議,但它仍然無法正常工作。你有關於這個問題的任何樣本項目嗎? – Joseph 2013-03-18 05:40:33

+0

我附上我的項目文件在這裏,請有人檢查了這一點,讓我知道是什麼問題:(http://cl.ly/091p3F3i3b3G – Joseph 2013-03-18 06:17:34

相關問題