2011-03-07 3 views
3

JAVA가 PHP 웹 서비스 프런트 엔드에 일련의 바코드를 보내야하는 학교 프로젝트에 참여하고 있습니다. 나는 두 게시물 herehere을 봤는데, 그들에게서 뭔가를 가져 왔지만, 내 코드가 작동하지 않는 것 같습니다.자바에서 Httppost를 통해 JSON을 보내는데 문제가 발생했습니다.

import org.json.simple.JSONObject; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.ResponseHandler; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.message.BasicHeader; 
import org.apache.http.protocol.HTTP; 
import org.apache.http.entity.StringEntity; 
import org.apache.http.HttpResponse; 
import java.io.InputStream; 


public class jsontest2 { 
    public static void main (String Args[]) { 
     JSONObject obj=new JSONObject(); 
     JSONObject codes=new JSONObject(); 
     //Forms the name value pairs for the barcodes and quantity 
     codes.put("598013", new Integer(10)); 
     codes.put("5849632927",new Integer(15)); 
     codes.put ("5849676037",new Integer(20)); 
     codes.put ("6634391931", new Integer(25)); 

     //Headers in the JSON array 
     obj.put("LoginID", new Integer(1234)); 
     obj.put("Machine_ID", new Integer(123456789)); 
     obj.put("add", codes); 
     System.out.print(obj); 

     //httppost 
     try { 
      HttpClient httpclient= new DefaultHttpClient(); 
      HttpResponse response; 
      HttpPost httppost= new HttpPost ("http://example/receive.php"); 
      StringEntity se=new StringEntity ("myjson: "+obj.toString()); 
      httppost.setEntity(se); 
      System.out.print(se); 
      httppost.setHeader("Accept", "application/json"); 
      httppost.setHeader("Content-type", "application/json"); 

      response=httpclient.execute(httppost); 

     } 
     catch (Exception e) { 
      e.printStackTrace(); 
      System.out.print("Cannot establish connection!"); 
     } 
    } 
} 

그리고 httppost 요청을 테스트하기 위해, 나는 모든 요청을 기록하려면이 PHP 파일을했습니다 :

그래서 여기 내 자바 코드입니다.

<?php 
$input = stripslashes($_POST["myjson"]); 
logToFile("post.txt", $input); 

function logToFile($filename, $msg) 
{ 
    $fd = fopen($filename, "a"); 
    $str ="[".date("Y/m/d h:i:s")."]".$msg; 
    fwrite($fd, $str."\n"); 
    fclose($fd); 
} 

이 문제는, 로그 파일 log.txt에에, 나는 JAVA 프로그램을 실행할 때마다, 그것은 단지 시간과 날짜로 구성된 새로운 라인을 추가합니다. 나에게 이것은 PHP가 httppost 요청을 받았음을 의미하지만 내 json 문자열은 어디에 있습니까?

아무도 내가 뭘 잘못하고 있다고 말할 수 있습니까? 나는 잠시 여기에 갇혀 있었다. 감사!

+0

'se'의 내용이 무엇인가에 JSON 개체에 대해 이해할 필요가? –

+0

[email protected] 및 var_dump ($ _ POST) = null입니다. –

+0

내 경우에 매우 simillar ... – gumuruh

답변

3

원시 HTTP 게시를하는 것처럼 보입니다. 따라서 PHP 코드는이를 고려해야합니다. PHP 코드의 경우이 시도 :

<?php 
$input = file_get_contents('php://input'); 
logToFile("post.txt",$input); 

function logToFile($filename,$msg) 
{ 
     $fd=fopen($filename,"a"); 
     $str="[".date("Y/m/d h:i:s")."]".$msg; 
     fwrite($fd,$str."\n"); 
     fclose($fd); 
} 
?> 

이 응답과 더 많은 정보를위한 다양한 링크를 참조하십시오 : PHP 모듈에서

php curl post json

+0

canuckistani, 덕분에 많은 도움을 주셔서 감사합니다! 왜 내가 $ _POST 대신 file_get_contents를 사용해야했는지 간단히 설명해 주시겠습니까? 다시 한 번 감사드립니다! –

+2

이 매뉴얼 페이지는 http://se2.php.net/wrappers.php입니다. 기본적으로, post 데이터가 name = value 쌍으로 인코딩되지 않은 경우 PHP는이를 $ _POST 배열로 구문 분석하지 않습니다. 이 경우 대신 입력 스트림을 사용하여 액세스해야합니다. – canuckistani

+0

나중에 모든 사람들이 언급 한 것과 같은 결과를 얻습니다. 나는 또한 호기심이있다. 이미 json으로 게시하고 있습니다. 어쨌든 @canuckistani : 대단히 감사합니다! – gumuruh

0

자바에서

  $username="demo"; 
    $action = 'error'; 
    $json =array('action'=> $action, 'username' => $username); 
    echo json_encode($json); 

문자열 regstatus = "";

BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));  

    String line; 
    while ((line = rd.readLine()) != null) { 

     regstatus =line; 
     String json="["+regstatus+"]" ; 
     JsonArray jArray = new JsonParser().parse(json).getAsJsonArray(); 
     for (int i=0;i<jArray.size();i++) { 
      JsonObject jsonObject = jArray.get(i).getAsJsonObject(); 
      System.out.println(jsonObject.get("username")); 
      System.out.println(jsonObject.get("action")); 
      System.out.println("*********"); 
     } 


    } 

'['(`) ($ _ POST`위해서 var_dump) (게시하기 전에)와`$ _POST` 자바

관련 문제