Unable to receive JSON POST request in PHP - java

I am passing a JOSN object from Java to PHP. I am using jdk 1.8 ang WAMP server.
Below is the Java code.
import java.io.IOException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.json.simple.JSONObject;
/**
*
* #author PReeeT Dash
*/
public class FromJava
{
public static void main(String[] args) throws IOException
{
JSONObject json = new JSONObject();
json.put("someKey", "someValue");
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
try
{
HttpPost request = new HttpPost("http://localhost/PGP/JSONReq/tophp.php");
StringEntity params = new StringEntity(json.toString());
request.addHeader("content-type", "application/json");
request.setEntity(params);
httpClient.execute(request);
// handle response here...
} catch (Exception ex)
{
System.out.println("Error: Cannot Estabilish Connection");
}
finally
{
httpClient.close();
}
}
}
PHP script:
$data = json_decode(file_get_contents("php://input"));
echo($data);
When I run the PHP file it always shows an Empty page. Can anyone please help me understand why is it not working.
When I run the following PHP code it always executes the else condition.
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$data = json_decode(file_get_contents("php://input"));
echo($data);
}
else
{
echo "XXXXXX";
}

I do not think this will work.
A PHP script is not "listening" as would a WebService. However, upon receiving the request, the script processes it and try to "print" the result in HTML, not Java.

Fetch the response body your org.apache.http.client instance receives and e.g. send it to System.out
CloseableHttpResponse response = httpClient.execute(request);
IOUtils.copy(response.getEntity().getContent(), System.out);
For IOUtils use import org.apache.commons.io.IOUtils;
In case you're using maven the dependency is
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
You will most likely get the output
Catchable fatal error<: Object of class stdClass could not be converted to string
because echo($data) doesn't work. json_decode(...) returns a stdClass.
Try
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
// json_decode(..., true) will return an array instead of a stdClass
$data = json_decode(file_get_contents("php://input"), true);
var_export($data);
}
else
{
var_export($_SERVER['REQUEST_METHOD']);
}
instead.

Related

HttpClientJava GET JSON not working properly

I'm trying to connect to my server by HTTP and obtain a JSON object, but it seems that I can't do it.
Here's my code:
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class Conector {
public static void main(String[] args) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpGet httpGet = new HttpGet("https://falseweb/select_all.php");
CloseableHttpResponse response1 = httpclient.execute(httpGet);
try {
System.out.println(response1.getStatusLine());
HttpEntity entity1 = response1.getEntity();
System.out.println(entity1.getContentEncoding());
EntityUtils.consume(entity1);
} finally {
response1.close();
}
} finally {
httpclient.close();
}
}
}
But instead of the JSON I get a printed null. I already tried the php file and it works, returning a json. Any idea what I'm doing wrong?.
The connection works because i got this message :
HTTP/1.1 200 OK
You seem to be logging out the content encoding as opposed to the actual content of the response which is probably why you aren't having any JSON joy.
Give the following a go (using Apache Commons IOUtils) :
System.out.println(IOUtils.toString(entity1.getContent(), "UTF8"));
If you can't use IOUtils then you can use any method of converting the InputStream into a String. More on that here.

Httpclient-4.5.2.jar setEntity showing "cannot find symbol" (JAVA - netbeans 8)

I am trying to use some code that I got from a website that has sports data served publically via an API (http://developer.fantasydata.com).
The site provide some sample JAVA code to make the http request. For some reason the setEntity method for the declared request (request) is showing a "cannot find symbol error.
package epl.fixtures.test.app;
import java.net.URI;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class EPLFixturesTestApp {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
HttpClient httpclient = HttpClients.createDefault();
try
{
URIBuilder builder = new URIBuilder("https://api.fantasydata.net/soccer/v2/json/CompetitionDetails/EPL");
URI uri = builder.build();
HttpGet request = new HttpGet(uri);
request.setHeader("Ocp-Apim-Subscription-Key", "****************");
// Request body
StringEntity reqEntity = new StringEntity("{body}");
request.setEntity(reqEntity);
HttpResponse response = httpclient.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null)
{
System.out.println(EntityUtils.toString(entity));
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
}
The line causing the issue is the request.setEntity(reqEntity); line
Can anyone explain this to me please? I have all the relevant jar files from apache added to the project libraries directory.
Thanks
HttpGet does not have a setEntity method.
This makes sense, since the request body has no meaning in GET requests.
Only classes implementing HttpEntityEnclosingRequest have this method.
I don't know why the documentation uses it, but it seems to work when omitting those two lines (which look meaningless anyway). Code:
URIBuilder builder = new URIBuilder("https://api.fantasydata.net/soccer/v2/json/CompetitionDetails/EPL");
URI uri = builder.build();
HttpGet request = new HttpGet(uri);
request.setHeader("Ocp-Apim-Subscription-Key", "****************");
HttpResponse response = httpclient.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null)
{
System.out.println(EntityUtils.toString(entity));
}

Unexpected char in the http get json file while using org.apache.http

There is a json file on my websites floder.
Here is the content:
{
"IsUpdateForcibly": "false",
"Version": "1.0",
"ReleaseNote": "OHOHOHOHOHO",
"DownloadLink": "http://192.168.1.37:11604/APK/FrauleinProject.apk"
}
If I use the browser to see,like http://localhost:11604/Content/CheckVersion.json, the result is same as thefile's content.
While I use the Java code. the response content is a little bit different.
?{
"IsUpdateForcibly": "false",
"Version": "1.0",
"ReleaseNote": "OHOHOHOHOHO",
"DownloadLink": "http://192.168.1.37:11604/APK/FrauleinProject.apk"
}
Why there is a question mark in the front of the string?
Here is is my httpclient code.
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import sun.misc.IOUtils;
import sun.net.www.http.HttpClient;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.WinHttpClients;
import org.apache.http.util.EntityUtils;
public class DesUtil {
public static void main(String[] args) throws Exception {
CloseableHttpClient httpclient = WinHttpClients.createDefault();
// There is no need to provide user credentials
// HttpClient will attempt to access current user security context through
// Windows platform specific methods via JNI.
try {
HttpGet httpget = new HttpGet("http://localhost:11604/Content/CheckVersion.json");
System.out.println("Executing request " + httpget.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httpget);
try {
System.out.println("----------------------------------------");
ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
#Override
public String handleResponse(
final HttpResponse response) throws ClientProtocolException, IOException {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
}
};
String json= new String(httpclient.execute(httpget, responseHandler).getBytes("ISO-8859-1"),"UTF-8");
PrintWriter out = new PrintWriter("filename.txt");
out.println(json);
out.close();
System.out.println(json);
JSONObject obj = JSONObject.fromObject(json);
System.out.println(obj==null);
Sb newSB= (Sb)JSONObject.toBean(obj,Sb.class);
System.out.println(newSB==null);
System.out.println(newSB.IsUpdateForcibly);
System.out.println(newSB.Version);
System.out.println(newSB.ReleaseNote);
System.out.println(newSB.DownloadLink);
}
catch(Exception ex){
System.out.println(ex.getMessage());
}
finally {
response.close();
}
}
catch(Exception ex){
System.out.println(ex.getMessage());
}
finally {
httpclient.close();
}
System.out.println("end");
}
}
I had a similar problem. I solved it by adding "UTF-8"
String str= EntityUtils.toString(entity2);
to
String str= EntityUtils.toString(entity2,"UTF-8");
demo:
private static void sendPost() throws ClientProtocolException, IOException
{
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://127.0.0.1:8911/crr");
ArrayList<NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("crawlId", "123"));
nvps.add(new BasicNameValuePair("transType", "0"));
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
CloseableHttpResponse response2 = httpClient.execute(httpPost);
try {
System.out.println(response2.getStatusLine());
HttpEntity entity2 = response2.getEntity();
String str= EntityUtils.toString(entity2,"UTF-8");
System.out.println(str);
} finally {
response2.close();
}
}
This probably stems from a Unicode BOM character, a zero-width space in Unicode that is used in UTF-8, UTF-16LE, UTF-16BE at the beginning of a file to mark it as Unicode: \uFEFF. It is redundant, unneeded, and - as seen here - causes several problems.
It was replaced with a question mark, as the character encoding of the saved text could not represent the BOM character.
As #zhizhi mentioned, better safe the JSON as UTF-8. Still better is to remove the BOM.
PrintWriter out = new PrintWriter("filename.txt", "UTF-8");
json = json.replaceFirst("^\uFEFF", "");
Mind that removing the BOM poses a UTF-8 recognition problem for Notepad.

search api of bing azure marketpalce with java

Tring to use search api of bing azure marketpalce with java
I have this code :
import org.apache.commons.codec.binary.Base64;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
public class BingAPI2 {
public static void main(String[] args) throws Exception{
BingAPI2 b = null;
b.getBing();
}
public static void getBing() throws Exception {
HttpClient httpclient = new DefaultHttpClient();
try {
String accountKey = "myAccountKey=";
byte[] accountKeyBytes = Base64.encodeBase64((":" + accountKey).getBytes());
String accountKeyEnc = new String(accountKeyBytes);
HttpGet httpget = new HttpGet("https://api.datamarket.azure.com/Data.ashx/Bing/Search/Web?$Query=%27Datamarket%27&$format=json");
httpget.setHeader("Authorization", "Basic <"+accountKeyEnc+">");
System.out.println("executing request " + httpget.getURI());
// Create a response handler
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httpget, responseHandler);
System.out.println("----------------------------------------");
System.out.println(responseBody);
System.out.println("----------------------------------------");
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
I get an error :
Exception in thread "main"
org.apache.http.client.HttpResponseException: The authorization type
you provided is not supported. Only Basic and OAuth are supported
first thing I see is that your line
byte[] accountKeyBytes = Base64.encodeBase64((":" + accountKey).getBytes());
should read :
byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":" + accountKey).getBytes());
also is there a reason you're using the apache libraries for this? the code I use for getting json objects from bing uses java.net and looks like this:
import java.net.URLConnection;
import java.net.URL;
import java.io.InputStreamReader;
class BingJson{
JSONObject getJSONfromBing(String term){
try{
URLConnection c = new URL(term).openConnection();
String key = (DatatypeConverter.printBase64Binary(("XXX" + ":" + "XXX").getBytes("UTF-8")));
c.setRequestProperty("Authorization", String.format("Basic %s",key));
c.connect();
//etc.
}
}
to build the json object I would say follow this code:
Convert InputStream to JSONObject

HTTP 403 Service Error when trying to post XML to HTTPS URL

I am trying to write a small class using the Apache HttpClient library that would do an HTTPS post to a specified URL sending some XML. When I run my code, the HTTP status line I receive back is "403 Service Error". Here's the complete error HTML returned:
$errorDump java.net.SocketTimeoutException:Read timed out
$errorInfo
$errorDump java.net.SocketTimeoutException:Read timed out
$error Read timed out
$localizedError Read timed out
$errorType java.net.SocketTimeoutException
$user
$time 2011-10-25 09:39:29 EDT
$error Read timed out
$errorType java.net.SocketTimeoutException
This is the code I am using:
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
public class HttpXmlPost {
public static void main(String[] args)
{
String url = "https://someurlhere.com";
String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><xmlTag></xmlTag>";
String content = request(xmlStr, url);
System.out.println(content);
}
private static String request(String xmlStr, String url) {
boolean success = false;
String content = "";
HttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httpPost = new HttpPost(url.trim());
InputStreamEntity reqEntity = new InputStreamEntity(new ByteArrayInputStream(xmlStr.getBytes() ), -1);
reqEntity.setContentType("application/xml");
reqEntity.setChunked(true);
httpPost.setEntity(reqEntity);
System.out.println("Executing request " + httpPost.getRequestLine());
HttpResponse response = httpclient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if(response.getStatusLine().getStatusCode() == 200){
success = true;
}
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
System.out.println("Chunked?: " + resEntity.isChunked());
}
BufferedReader reader = new BufferedReader(new InputStreamReader(resEntity.getContent()));
StringBuilder buf = new StringBuilder();
char[] cbuf = new char[ 2048 ];
int num;
while ( -1 != (num=reader.read( cbuf ))) {
buf.append( cbuf, 0, num );
}
content = buf.toString();
EntityUtils.consume(resEntity);
}
catch (Exception e) {
System.out.println(e);
}
finally {
httpclient.getConnectionManager().shutdown();
}
return content;
}
}
Whatever XML I pass in doesn't seem to matter, it gives the same error no matter what. Note that this actually works with some URLs. For example, if I put https://www.facebook.com, it goes through. However, it doesn't work for my specified URL. I thought it might be a certificate issue, tried to add some code to trust any certificate, didn't seem to work either, though I may have done it wrong. Any help is appreciated.
Based on the SocketTimeoutException in the first line of the response HTML, I'm guessing that the component which implements the handler for the URL to which you are posting is having some connection problems to a source system it needs to generate the response data.
Basically, it looks like the problem is on the server, not your client.

Categories