I've got the following base structure:
And now I want to add some data to articles node. For example :
{"title":"Test","content":"Test text","keyWords":"1,2,3","date":"Aug 14, 2015 5:52:16 PM"}
Firebse REST API documentation says, that I should POST data, but log writes
Server returned HTTP response code: 400 for URL:
https://$TEST-BASE.firebaseio.com/articles.json?auth=$TOKEN
$TEST-BASE and $TOKEN are valid parameters. I can clearly see the GET response. What is wrong? The code:
public class JSONTest {
public static void main(String[] args) throws IOException {
post("{\"title\":\"Test\",\"content\":\"Test text\",\"keyWords\":\"1,2,3\",\"date\":\"Aug 14, 2015 5:52:16 PM\"}", "https://<TEST-BASE>.firebaseio.com/articles.json?auth=<TOKEN>");
}
private static void post(String json, String urlString) {
OutputStreamWriter out = null;
try {
URL url = new URL(urlString);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("POST");
out = new OutputStreamWriter(
httpCon.getOutputStream());
System.out.println(json);
out.write(json);
httpCon.getInputStream();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
I wish I had enough reputation points to just leave a comment =P , but I believe the reason why you're getting the 400 is because you're not sending your data to the right end-point. Try stripping the .json from the URL:
https://<TEST-BASE>.firebaseio.com/articles?auth=<TOKEN>
Related
I have a simple web api which receives a parameter as string and return a "success" string as response.
I have tested the api url with POSTMAN App and I got response as "success"
url : http://www.xxx.co/testapi/testmethod
Method : POST
Params : key=val ; value=Hai
Postman return as : "success"
My code in android is:
public static String tryPOSTScript(){
Log.d("TAG","App1 inside tryPOSTScript");
String data = "val=Hai";
URL url = null;
try {
url = new URL("http://www.xxx.co/testapi/testmethod");
} catch (MalformedURLException e) {
Log.d("TAG","App1 Exception MalformedURLException: "+e.toString());
e.printStackTrace();
}
HttpURLConnection con = null;
try {
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.getOutputStream().write(data.getBytes("UTF-8"));
con.getInputStream();
} catch (IOException e) {
Log.d("TAG","App1 Exception IOException: "+e.toString());
e.printStackTrace();
}
return data;
}
And I got the response as
Exception IOException: java.io.FileNotFoundException: http://www.xxx.co/testapi/testmethod
Exception responseCode: 404
Please help to correct it. If file not found How can I get it correctly with postman app?
I don't know what is wrong with my code I keep getting error 401 when I try making a request to the GitHub. My app uses the REST API before now I and to convert it to the Graphql but I am finding it difficult
private static String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
// If the URL is null, then return early.
if (url == null) {
return jsonResponse;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestProperty("Authorization","Bearer token");
urlConnection.setRequestProperty("Content-Type", "application/json");
DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream());
wr.writeBytes("{\"query\":\"query{search(type:USER query:\"location:lagos language:java\"){userCount}}}");
wr.flush();
wr.close();
int rc = urlConnection.getResponseCode();
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} catch (IOException e) {
Log.e(LOG_TAG, "Problem retrieving the earthquake JSON results.", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
inputStream.close();
}
}
return jsonResponse;
}
Found the mistake
There was a problem with my token and the query format was wrong it should have been
"{\"query\": \"query { search ( type : USER, query : \\\"location:lagos\\\" ) { userCount }}\"}"
Thank for your suggestion
The Authorization header token might not be valid. HTTP 401 = not authorized.
I'd suggest trying to make same request with a Curl and when you see success - apply same parameters/headers to HttpUrlConnection.
I am trying to send json string from my android app to my php server. Below is the complete code from my mobiledb_control.php and httpconnect.java
The Log.v("HTTPSENDER","WORKED"); runs, and I get no errors.
However my error_log("in"); does not run.
How do I display the JSON sent via android into my error_log() ?
HttpConnect.java:
public class HttpConnect {
public HttpConnect(){
}
public void sendData(String jsonObject){
try{
URL url = new URL("http://www.alextanti.net/PHPDashboard/Backend/mobiledb_control.php");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(),"UTF-8"));
output.write("json="+jsonObject);
output.flush();
output.close();
Log.v("HTTPSENDER","WORKED");
}catch(Exception e){
e.printStackTrace();
}
}
}
mobiledb_control.php:
<?php
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set("error_log", "../Logs/error.log");
error_reporting(E_ALL);
if(!empty($_POST['json'])){
echo(var_dump($_POST['json']));
error_log($_POST['json']);
}
$headers = apache_request_headers();
?>
try this in PHP code
and turn on error reporting like this
// Report all PHP errors (see changelog)
error_reporting(E_ALL);
and
print_r($_POST);
for more clarification what you are getting from post.
use encode and decode functions of php for making and parsing json.
$request=json_decode($_POST['json']); // it gives the Array
foreach($request as $values){
echo($values['your_value1'])
echo($values['your_value2'])
}
please refer this url : http://php.net/manual/en/function.json-decode.php
Seemed to have fixed it but I have no idea how
PHP File:
<?php
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set("error_log", "../Logs/location.log");
error_reporting(E_ALL);
if(!empty($_POST['json'])){
echo(var_dump($_POST['json']));
error_log($_POST['json']);
}
?>
JAVA File:
public class HttpConnect {
public HttpConnect(){
}
public void sendData(String jsonObject){
try{
URL url = new URL("http://www.alextanti.net/PHPDashboard/Backend/mobiledb_control.php");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(),"UTF-8"));
output.write("json="+jsonObject);
output.flush();
output.close();
Log.v("HTTPSENDER","WORKED");
Log.v("HTTPSENDER",""+conn.getResponseCode());
}catch(Exception e){
e.printStackTrace();
}
}
}
In designing server-client communication, it is imperative to make sure both client and server can communicate with each other. With that in mind, can you please provide the server response code by adding this in your code inside try block:
try {
...
Log.d(TAG, "code: " + conn.getReturnCode());
InputStream is = conn.getInputStream();
String serverReply = readIt(is, 500);
Log.d(TAG, serverReply);
...
}
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
It will return 200 and 401 respectively. Returns -1 if no code can be
discerned from the response (i.e., the response is not valid HTTP).
Cheers!
I have the following code in my program, used for inserting record -
private Void downloadUrl() throws IOException {
String postParameters;
HttpURLConnection urlConnection = null;
postParameters = "name="+ URLEncoder.encode(user.name,"UTF-8")
+"&age="+URLEncoder.encode(user.age+"","UTF-8")
+"&username="+URLEncoder.encode(user.username,"UTF-8")
+"&password="+URLEncoder.encode(user.password,"UTF-8");
if (postParameters != null) {
Log.i("Post", "POST parameters: " + postParameters);
try {
URL urlToRequest = new URL(SERVER_ADDRESS);
urlConnection = (HttpURLConnection) urlToRequest.openConnection();
urlConnection.setReadTimeout(30000 /* milliseconds */);
urlConnection.setConnectTimeout(30000 /* milliseconds */);
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
urlConnection.setFixedLengthStreamingMode(
postParameters.getBytes().length);
PrintWriter out = new PrintWriter(urlConnection.getOutputStream());
out.print(postParameters.getBytes());
out.close();
// handle issues
int statusCode = urlConnection.getResponseCode();
Log.e("Response", "The response is: " + statusCode);
} catch (MalformedURLException e) {
// handle invalid URL
Log.e("Response", "invalid URL");
} catch (SocketTimeoutException e) {
// hadle timeout
Log.e("Response", "handle timeout");
} catch (IOException e) {
// handle I/0
Log.e("Response", "handle IO problem");
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
return null;
}
The code is showing no errors and the logged entries are
09-27 12:24:17.944 5006-5039/? E/Response﹕ The response is: 200
09-27 12:24:33.729 5006-5118/? I/Post﹕ POST parameters: name=vibha&age=25&username=vib&password=1234
But when I check the database, the new record is not created.
But if I use PHP code in a file and post the same parameters,the records are getting inserted.
My requirement for help and guidance is how to pass the post parameter in the HttpURLConnection class
In my java application I used a Httpsurlconnection to post some string data to the server. When I test this code on android, it works perfectly. However, in a java application it does not work. Client java application is as follows:
public static void main(String[] args) {
disableSslVerification();
new HttpsClient().testIt();
}
private void testIt() {
String https_url = "https://XXX.XX.XXX.XXX:XXXX/XXXXX/TestServlet";
URL url;
try {
url = new URL(https_url);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
print_content(con, "test");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void print_content(HttpsURLConnection connection, String data) {
if (connection != null) {
try {
connection.setConnectTimeout(6000);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
Charset cSet = Charset.forName("UTF-8");
byte bytes[] = data.getBytes(cSet);
connection.setRequestProperty("Content-Length", ""
+ Integer.toString(bytes.length));
connection.setRequestProperty("Content-Language", "tr");
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream());
wr.write(bytes);
wr.flush();
wr.close();
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is, cSet));
String line;
StringBuilder response = new StringBuilder();
while ((line = rd.readLine()) != null) {
response.append(line);
response.append(System.getProperty("line.separator"));
}
rd.close();
System.out.println(response.toString());
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}
And the servlet is as follows:
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String s = getHTML(request);
try {
out.print("received data:");
out.print(s);
} finally {
out.close();
}
}
private String getHTML(HttpServletRequest request) throws IOException {
int n = request.getContentLength();
if (n < 1) {
return "";
}
byte bytes[] = new byte[n];
request.getInputStream().read(bytes);
return new String(bytes, "UTF-8");
}
When I run this application, servlet's response is:
received data:t☐☐☐
Always only the first character is correctly send to the servlet. The same code works perfect on android. Can anyone help me please? Thanks...
I can't see an obvious problem with your code that would cause this.
Can anyone help me please?
I suggest that you take a methodical approach to investigating the problem. Use a packet sniffer to check what is actually being sent over the wire. Check that the actual headers in the request and response are correct. Check that the request and response bodies are really properly encoded UTF-8 ...
What you find in your investigation / evidence gathering will help you figure out where the problem (or problems) are occurring ... and that will allow you to home in on the part(s) of your code that is/are responsible.
request.getInputStream().read(bytes);
You might need to do this read in a loop. At the very least, check how many bytes have been read. The array appears to be empty except for the first char.
Reads some number of bytes from the input stream and stores them into
the buffer array b. The number of bytes actually read is returned as
an integer. This method blocks until input data is available, end of
file is detected, or an exception is thrown.