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();
Related
Im trying to send a post to a backend API from android and this is what I have but some special characters relating to application/x-www-form-urlencoded content type wont be sent or cause problems. Im wondering if there is a way to send the special characters in this format? (+,&) I'm attempting to send the message "This is a message + a test" but my database is getting "This is a message a test"
I've tried passing JSON but the backend that my co-students wrote doesn't accept JSON and returns a 401 not authorized error.
public void sendMessage() {
if(!mEdit.getText().toString().trim().matches("")) { //Cant send empty strings
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
URL url = new URL(Sendurl); //Create URL
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //Create a Connector
conn.setRequestMethod("POST"); //Dictate the Method
conn.setRequestProperty("Content-Type", "application/json; utf-8"); //Some other properties
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
//This part causes a 401 error because it is the equivalent of passing parameters but our backend uses body formatting
JSONObject jsonParam = new JSONObject();
Date date = new Date();
RequestParams params = new RequestParams();
params.put("username", "admin");
params.put("sessionID", 1);
params.put("cardNum", 111111111);
params.put("sentByStaff", "false");
params.put("message", "This is the message + a test");
params.put("time", date.getTime()/1000);
Log.i("JSON", params.toString());
// OutputStreamWriter os = new OutputStreamWriter(conn.getOutputStream()); //Prepare the connection for output
POST_PARAMS = params.toString(); //Converts post parameters to body type
System.out.println(POST_PARAMS);
try(OutputStream os = conn.getOutputStream()) {
byte[] input = POST_PARAMS.getBytes("utf-8");
os.write(input, 0, input.length);
os.flush();
os.close();
}
//os.write(POST_PARAMS); //Write our parameters to the post
//os.flush(); //Do the thing
//os.close();
Log.i("STATUS", String.valueOf(conn.getResponseCode())); //Debug
Log.i("MSG", conn.getResponseMessage()); //Debug
int responseCode = 0; //get response code
responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { //On success
mEdit.setText("");
}
conn.disconnect(); //disconnect after attempting post
getMessage(); //update our messages
} catch (Exception e) { //dirty catch all
e.printStackTrace();
}
}
});
thread.start();
}
}
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.
I have problem with connecting to my server. Following code returns -1 as response code and null as response message.
protected Boolean doInBackground(MyTaskParams... params) {
URL url = null;
String load = params[0].jobj.toString();
try {
url = new URL(params[0].serverUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(3000);
urlConnection.setReadTimeout(3000);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
urlConnection.setChunkedStreamingMode(0);
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
OutputStreamWriter osw = new OutputStreamWriter(urlConnection.getOutputStream());
osw.write(load);
osw.flush();
osw.close();
if(urlConnection.getResponseCode()==200 && urlConnection.getResponseMessage().contains("true") ) return true;
else return false;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
While debbuging url and body content (which is load in code) are correct. When I try to connect with the server using those params with Fiddler it works perfectly and I get 200 status code. Do you have any ideas what is wrong?
Im passing jData object as the jobj:
JSONObject User=new JSONObject();
JSONObject Mobile=new JSONObject();
JSONObject jData=new JSONObject();
try {
User.put ("UserLogin", "test");
User.put ("UserPassword", "test");
Mobile.put ("MobileIDD", IDD);
Mobile.put("MobileToken", token);
jData.put("Mobile", Mobile);
jData.put("User", User);
} catch (JSONException e) {
e.printStackTrace();
}
#EDIT
Solution with System.setProperty("http.keepAlive", "false") didnt help.
I solved the problem. It was in this line:
if(urlConnection.getResponseCode()==200 && urlConnection.getResponseMessage().contains("true") ) return true;
When I changed it to:
int code = urlConnection.getResponseCode();
if (code==200.....)
It started working.
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());
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'];