JAVA가 PHP 웹 서비스 프런트 엔드에 일련의 바코드를 보내야하는 학교 프로젝트에 참여하고 있습니다. 나는 두 게시물 here과 here을 봤는데, 그들에게서 뭔가를 가져 왔지만, 내 코드가 작동하지 않는 것 같습니다.자바에서 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 문자열은 어디에 있습니까?
아무도 내가 뭘 잘못하고 있다고 말할 수 있습니까? 나는 잠시 여기에 갇혀 있었다. 감사!
'se'의 내용이 무엇인가에 JSON 개체에 대해 이해할 필요가? –
[email protected] 및 var_dump ($ _ POST) = null입니다. –
내 경우에 매우 simillar ... – gumuruh