HTTP POST method says 404 file not found exception on Android - java

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?

Related

How to read HTML from URL.openStream() after 500 return code causes exception?

I'm creating an educational terminal application that is fetching a website via URL.openStream(). Based on the query, the page might return a 500 error code. However, there is a valuable error description in the body which I would like to display.
Unfortunately, URL.openStream() throws IOException when it encounters the return code 500, and I have no way to read the stream once the exception is caught.
BufferedReader in = null;
try {
URL url_connection = new URL(url);
in = new BufferedReader(new InputStreamReader(url_connection.openStream()));
} catch (IOException e) {
}
The variable in will stay null because the exception is thrown before the openStream returns.
How to read the HTML code from the HTTP response?
I found a solution by using HttpURLConnection, which has a method called getErrorStream():
HttpURLConnection conn = null;
try {
URL url_connection = new URL(url);
conn = (HttpURLConnection) url_connection.openConnection();
System.out.println(new String(conn.getInputStream().readAllBytes()));
} catch (IOException e) {
System.out.println(new String(conn.getErrorStream().readAllBytes()));
}

How to fix error code 500 when using HttpURLConnection GET request with header? Header is not being sent

I am trying to send a GET request with a header, but the header is not being send and I am receiving error code 500. ttps://skyscanner-skyscanner-flight-search-v1.p.rapidapi.com/apiservices/browsequotes/v1.0/US/USD/en-US/SFO-sky/JFK-sky/2019-09-01.
I have tried several variations such as the depreciated apache, HttpURLConnection, and volley. I always end up getting error code 500. I have added the permissions in manifest. I tested the API GET request on Postman and it works fine as you can see here: http://prntscr.com/n2tv2e
public void buttonHandler(View v)
{
try {
URL url = new URL("https://skyscanner-skyscanner-flight-search-v1.p.rapidapi.com/apiservices/browsequotes/v1.0/US/USD/en-US/SFO-sky/JFK-sky/2019-09-01");
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setRequestProperty("X-RapidAPI-Key", "jkjkjkjkjkjkjkjkjkjkj");
con.setRequestMethod("GET");
InputStream inputStream = con.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line = bufferedReader.readLine();
textView.setText(line);
con.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I want the json file as shown here: http://prntscr.com/n2tv2e
You need to add header like this
HttpPost post = new HttpPost( "URL" );
post.addHeader( "Key" , "Value" );

Firebase responses 400

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>

HTTP URL redirect status code

The url which I give gets redirected. When i hit the url with some browser it redirects to another site. When i test it in some rest client i am getting http code 302, which is correct for redirect. But i try the same with below code, it returns 200. Can somebody help me out ?Thanks in advance.
updated url.
try {
URL url = new URL("https://securestore.hbo.com/cart.php?f=pplogin&ppx=1&method=checkout");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
int code = connection.getResponseCode();
System.out.println(connection.getResponseMessage());
System.out.println("code is" + code);
connection.disconnect();
}
catch (MalformedURLException e) {
e.printStacTrace();
}
catch (IOException e) {
e.printStackTrace();
}
If url1 is being redirected to url2, then you will get 302 status. However if you code is directally calling url2, you are bound to get 200.
Try the following code.
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
.....
connection = (HttpConnection)Connector.open(url);
responseCode = connection.getResponseCode();
Try adding a response with the 302 code you want. Something like connection.setStatus(statusCode) I may be wrong though.
The HttpURLConnection will follow the redirects by default.
Try setting the following if you do not wish to follow redirects:
HttpURLConnection.setFollowRedirects(false);
For example, in relation to your code:
try {
URL url = new URL("");
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
int code = connection.getResponseCode();
System.out.println(connection.getResponseMessage());
System.out.println("code is" + code);
connection.disconnect();
}
catch (MalformedURLException e) {
e.printStacTrace();
}
catch (IOException e) {
e.printStackTrace();
}

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());

Categories

Resources