Sending JSON from Java HTTPUrlConnection, but $_POST variable is empty in PHP? - java

I'm writing an Android app and I want to send some JSON data to a PHP server. The POST request does go to the server but in my server.php script I check the $_POST variable and it is empty. TCP/IP monitor is not in Eclipse ADT and wireshark doesn't show localhost request so I can't see what is actually being sent. So does anyone have an idea what is being sent and how I can access it in PHP? Or have I made a mistake in the code somewhere?
JSONObject json = new JSONObject();
try {
json.put("dog", "cat");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
HttpURLConnection urlConnection = null;
try {
URL url = new URL("http://10.0.2.2/server.php");
urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
OutputStreamWriter os = new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8");
os.write(json.toString());
os.close();
}

try it.
JSONObject json = new JSONObject();
try {
json.put("dog", "cat");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
HttpClient localDefaultHttpClient=new DefaultHttpClient();
HttpPost lotlisting = new HttpPost("http://10.0.2.2/server.php");
ArrayList localArrayList = new ArrayList();
localArrayList.add(new BasicNameValuePair("json",json.toString()));
try {
lotlisting.setEntity(new UrlEncodedFormEntity(localArrayList));
String str = EntityUtils.toString(localDefaultHttpClient.execute(lotlisting).getEntity());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
you will get the output in str variable;

I think is missing the flush
Try os.flush(); after os.write(..)

Don't use $_POST. Do something like this on user server
$json = file_get_contents('php://input');
$animals= json_decode($json,true);
//you can do
echo $animals['dog'];

Related

How to send such json post request in java with param in the url?

I have such a data. I don't know how to write it in java to send a post JSON request. Please help me! I can do it with curl in Windows, the code is:
curl -X POST -H "Content-Type:application/json" -d "[{\"hostId\": \"01a31fc518c44166afe29a8694f4b3e8\",\"host\": \"WIN-PC_tttqa\",\"metric\": \"system.cpu.used1232\",\"timestamp\": 1457577649000,\"value\": 0,\"tags\": [\"location:aa\",\"level:high\"],\"type\": \"gauge\"}]" http://ip:port/openapi/v2/datapoints?api_key=fe01ce2a7fbac8fafaed7c982a04e229
data format
You can see the data format in the img link of "data format", please show me the code, then I will try it immediately.
This is my test function:
public void sendPost() throws JSONException {
HttpURLConnection connection = null;
try {
// 创建连接
URL url = new URL(ADD_URL);
connection = (HttpURLConnection) url.openConnection();
// 设置http连接属性
connection.setDoOutput(true);
connection.setRequestMethod("POST");
// 设置http头 消息
connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
connection.setRequestProperty("Accept", "application/json");
// 添加 请求内容
JSONArray jsonArray = new JSONArray();
JSONObject json = new JSONObject();
json.put("api_key", "fe01ce2a7fbac8fafaed7c982a04e229");
json.put("hostId", "01a31fc518c44166afe29a8694f4b3e8");
json.put("host", "WIN-PC240");
json.put("metric", "system.cpu.used1232");
json.put("value", 0);
JSONArray array = new JSONArray();
array.put("location:aaa");
array.put("level:high");
json.put("tags", array);
json.put("type", "gauge");
jsonArray.put(json);
System.out.println(jsonArray.toString());
OutputStream out = connection.getOutputStream();
out.write(jsonArray.toString().getBytes());
out.flush();
out.close();
// 读取响应
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String lines;
StringBuffer sb = new StringBuffer("");
while ((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes(), "utf-8");
sb.append(lines);
}
reader.close();
// // 断开连接
connection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I made a mistake. I thought post request can't follow "?param=..." in the URL. I just need to put the "api_key" in the URL instead of putting it in the JSON parameters.

POST Android json data

I'm trying to POST some data to my server, but I don't know why, I always get 400 messages from it.
I want to send this POST structure:
POST /api/v0.1/observations/3 HTTP/1.1
Host: 54.154.117.132`
Content-Type: application/json
Cache-Control: no-cache
{
"data" :
{
"field1" : 1111111
},
"timestamp": "2015-05-13T12:23:42.648738"
}
If I send that with curl, or wget, I get a 200 Http status.
I'm doing this on android:
public void POST(String json) throws MalformedURLException {
int httpResult;
//URL url = new URL(getString(R.string.URL));
URL url = new URL(getString(R.string.URL_test2));
HttpURLConnection con;
JSONObject obj1 = new JSONObject();
JSONObject obj2 = new JSONObject();
try {
obj1.put("field1",222);
obj2.put("data", obj1);
obj2.put("timestamp", "2015-06-8T12:05:42.648738");
} catch (JSONException e) {
e.printStackTrace();
}
try {
con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setUseCaches(false);
con.setConnectTimeout(10000);
con.setReadTimeout(10000);
con.setRequestProperty("Content-Type","application/json");
con.setRequestProperty("Host", "54.154.117.132");
con.connect();
OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
out.write(obj2.toString());
out.close();
httpResult = con.getResponseCode();
Log.i("Request","--> "+httpResult);
if (httpResult == HttpURLConnection.HTTP_OK) Log.i("HTTP"," --> all ok");
else Log.i("HTTP", " --> smthg wrong!");
} catch (IOException e) {
Log.i("ERROR"," !!! Interrupcion a la hora de conectarse");
}
}
I don't know if this is exactly the same structure, that's is my conclusion, because using Postman on chrome, and curl or wget, get 200 status.
Someone can help me?
The URL if you want to try is on POST method on the top.
Add your params in JSONObject like below:
JSONObject jsonObject = new JSONObject();
jsonObject .put("field", 222);
JSONObject mainObject = new JSONObject();
try {
mainObject .put("data",jsonObject);
mainObject .put("timestamp","2015-05-13T12:23:42.648738");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
And change here in code:
OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
out.write(mainObject.toString()); //change to mainObject from obj2
out.close();

Parse.com REST API Error Code 400: Bad Request from Java HTTP Request to Cloud Function

I have a string that I am trying to send to a Parse.com cloud function. According to the REST API documentation (https://www.parse.com/docs/rest#general-requests), it must be in json format, so I made it into a json object and converted it to a string to append to the end of the http request url.
JSONObject jsonParam = new JSONObject();
jsonParam.put("emailId", emailId);
String urlParameters = jsonParam.toString();
Then I send the request as so, in my attempt to match their cURL code example as Java code:
con.setDoOutput(true);
DataOutputStream wr = null;
wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
Nonetheless, I receive a returned error code of 400 with error message "Bad Request", which I believe to be caused by unrecognizable parameters being sent to the cloud function. None of the other errors in my code trigger. Yet I verified through console logs that emailId is a normal string and the resulting JSON object, as well as its .toString() equivalent comes out as a proper string reading of a JSON object. Also this worked for another function I have in which I am creating an object in my Parse database. So why would it not work here?
Here is the full function for reference and context:
private void sendEmailWithParse(String emailId) throws IOException {
String url = "https://api.parse.com/1/functions/sendEmailNow";
URL obj = new URL(url);
HttpsURLConnection con = null;
try {
con = (HttpsURLConnection) obj.openConnection();
} catch (IOException e) {
System.out.println("Failed to connect to http link");
e.printStackTrace();
}
//add request header
try {
con.setRequestMethod("POST");
} catch (ProtocolException e) {
System.out.println("Failed to set to POST");
e.printStackTrace();
}
con.setRequestProperty("X-Parse-Application-Id", "**************************************");
con.setRequestProperty("X-Parse-REST-API-Key", "************************************************");
con.setRequestProperty("Content-Type", "application/json");
JSONObject jsonParam = new JSONObject();
jsonParam.put("emailId", emailId);
System.out.println("parameter being sent to cloud function: " + jsonParam);
System.out.println("parameter being sent to cloud function as string: " + jsonParam.toString());
String urlParameters = jsonParam.toString();
// Send post request
con.setDoOutput(true);
DataOutputStream wr = null;
try {
wr = new DataOutputStream(con.getOutputStream());
} catch (IOException e1) {
System.out.println("Failed to get output stream");
e1.printStackTrace();
}
try {
wr.writeBytes(urlParameters);
} catch (IOException e) {
System.out.println("Failed to connect to send over Parse object as parameter");
e.printStackTrace();
}
try {
wr.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
wr.close();
} catch (IOException e) {
System.out.println("Failed to connect to close datastream connection");
e.printStackTrace();
}
int responseCode = 0;
try {
responseCode = con.getResponseCode();
} catch (IOException e) {
System.out.println("Failed to connect to get response code");
e.printStackTrace();
}
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
System.out.println("Response message: " + con.getResponseMessage());
}
I solved the problem by using the HttpRequest external library. It gave me better control of the request and made for easier debugging of the problem. The server was receiving the request just fine, the problem was with the JSON encoding. Rather than putting the JSON object as a parameter in the request, I inserted it into the body of the http request and encoded it in UTF-8.
In the end, this is the code that worked:
String url = "https://api.parse.com/1/functions/sendEmailNow";
URL obj = new URL(url);
//Attempt to use HttpRequest to send post request to parse cloud
HttpRequest request = HttpRequest.post(obj).contentType("application/json");
request.header("X-Parse-Application-Id", "**************************");
request.header("X-Parse-REST-API-Key", "********************");
JSONObject jsonParam = new JSONObject();
jsonParam.put("emailId", emailId);
request.send(jsonParam.toString().getBytes("UTF8"));
if (request.ok())
System.out.println("HttpRequest WORKED");
else
System.out.println("HttpRequest FAILED " + request.code() + request.body());

How to get info from HttpResponse java?

First of all please look at my code below:
List<BasicNameValuePair> qsList = new ArrayList<BasicNameValuePair>();
qsList.add(new BasicNameValuePair("oauth_token", accessToken));
String queryString = URLEncodedUtils.format(qsList, HTTP.UTF_8);
HttpGet userInfoRequest = new HttpGet(id + "?" + queryString);
DefaultHttpClient defaultHttpClientclient = new DefaultHttpClient();
HttpResponse userInfoResponse;
try {
userInfoResponse = defaultHttpClientclient.execute(userInfoRequest);
String responseBody = EntityUtils.toString(userInfoResponse.getEntity());
System.out.println("User info response: " + responseBody);
System.out.println("");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I got an access token from Salesforce. Now I request user's information via that token. In the responseBody I got all infomation of that user like username, id, language,... Now I need to take only username from the response. What should I do to take it?
The response is likely in JSON. If so you can parse the data you need. I won't repost the code, instead please see: How to parse JSON in Java
JSONObject responseJSON = new JSONObject(EntityUtils.toString(userInfoResponse.getEntity());
String username = responseJSON.getString("username");

Android: cannot instantiate the type httpclient

I am getting an error with the following line of code
HttpClient Client= new HttpClient, event I have add httpclient-4.2.3.jar to my project.
I have tried rewriting it as HttpClient Client= new DefaultHttpClient. But it solves the problem and creates a new error with other methods (in executeMethod()).
This is my code :
public static String POSTUpload(String url, String foto){
InputStream inputStream=null;
String result="";
HttpClient httpClient = new HttpClient();
PostMethod method = new PostMethod(url);
//set JSON ke hhtp post entity
// File file_foto= new File(foto);
// FileEntity fe_foto=new FileEntity(file_foto, "image/jpeg");
method.setRequestEntity(new FileRequestEntity(new File(foto), "multipart/form-data"));
// se.setContentType("application/json;charset=UTF-8");
// httpPost.setHeader("Accept", "application/json");
try {
int status = httpClient.executeMethod(method);
System.out.println("HTTP status " + method.getStatusCode()
+ " creating con\n\n");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace(); // TODO Auto-generated catch block
}finally {
method.releaseConnection();
}
}
is there anyone know why this is happen? Please Help

Categories

Resources