How to post x-www-form-urlencoded post request? - java

I am having troubles with posting http POST request in java. All the details are correct, but I am getting error for not valid API key.
I tried everything, and read every single post that I could find here but still no clue what is incorrect.
Here's the code:
String urlString = "https://example.com/";
url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
String data = URLEncoder.encode("api_key", "UTF-8")
+ "=" + URLEncoder.encode("xxxxx", "UTF-8");
urlConnection.connect();
OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(data);
wr.flush();
try{
stream = urlConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"), 8);
String result = reader.readLine();
System.out.println(result);
} catch (IOException e){
throw(new Throwable("An error occured:\n" + e));
}

Related

Calling an API that have username and password in Java

I'm trying to connect to an API that has a username and password with this code:
try {
URL url = new URL("https://url?UserName=username&Password=password");
Connection = (HttpURLConnection) url.openConnection();
//Request setup
Connection.setRequestMethod("GET");
Connection.setConnectTimeout(5000);
Connection.setReadTimeout(5000);
int status = Connection.getResponseCode();
System.out.println(status);
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
But I get the error:
java.net.SocketException: Connection reset
I kept searching and I found another format for the URL which is:
URL url = new URL("Https:username:password#url);
When I tried, it gave me the error:
java.net.MalformedURLException: For input string:password#url
I tried to separate the URL into three strings and made the password Integer.pharsInt("String"), but it also didn't work.
The password has words, numbers, and a special character!
What am I doing wrong?
Try to encode your URL, this way:
HttpURLConnection connection = (HttpURLConnection)
new URL("https://url?UserName" +
URLEncoder.encode(username, "UTF-8") +
"&Password=" +
URLEncoder.encode(password, "UTF-8"))
.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json");
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));
// The rest of your code

Calling Post request without body in java

I have a post API which doesn't accept any input. I have to get output from API. But it is giving compilation error.
HttpURLConnection connection = null;
String targetUrl="https://idcs-oda-9417f93560b94eb8a2e2a4c9aac9a3ff-t0.data.digitalassistant.oci.oc-test.com/api/v1/bots/"+BotID+"/dynamicEntities/"+dynamicEntityId+"/pushRequests
URL url = new URL(targetUrl);
connection=(HttpURLConnection) url.openConnection();
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
connection.setRequestProperty("Authorization", "Basic aWRjcy1vZGEtOTQxN2Y5MzU2MGI5NGViOGEyZTJhNGM5YWFjOWEzZmYtdDBfQVBQSUQ6MjQ0YWU4ZTItNmY3MS00YWYyLWI1Y2MtOTExMDg5MGQxNDU2");
connection.setRequestProperty("Accept", "application/json");
OutputStream os = connection.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
**osw.write();** //this line is expecting input in parameter
osw.flush();
osw.close();
os.close();
connection.connect();
If I dont pass any value in osw.write() it gives compilation error. How can I resolve the same.
Look at the following method for the post call. You will need to add the outputstream to the osw.write() as it expects a parameter.
private static void sendPOST() throws IOException {
URL obj = new URL(POST_URL);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
// For POST only - START
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
// For POST only - END
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
}
else {
System.out.println("POST request not worked");
}
}
For more details on the above code look here.

EDIT: How do I send this post Request with parameters AND form-data like this postman screenshot in JAVA?

I'm trying to send a POST request to grab comments but it doesn't work in Java while it does work with postman.
I get an 403 Forbidden error, but on postman it retrieves the data i need just fine..
Here's the Java code I'm trying to use to replicate the behavior.
String targetUrl = YOUTBE_COMMENTS_AJAX_URL;
String urlParameters = "action_load_comments=1&order_by_time=True&filter=jBjXVrS8nXs";
String updatedURL = targetUrl + "?" + urlParameters;
URL url = null;
InputStream stream = null;
HttpURLConnection urlConnection = null;
try {
url = new URL(updatedURL);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("content-type", "multipart/form-data");
urlConnection.setRequestProperty("user-agent", "USER_AGENT");
urlConnection.setDoOutput(true);
String data = URLEncoder.encode("video_id", "UTF-8")
+ "=" + URLEncoder.encode(youtubeId, "UTF-8");
data += "&" + URLEncoder.encode("session_token", "UTF-8") + "="
+ URLEncoder.encode(xsrfToken, "UTF-8");
data += "&" + URLEncoder.encode("page_token", "UTF-8") + "="
+ URLEncoder.encode(pageToken, "UTF-8");
urlConnection.connect();
OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(data);
wr.flush();
stream = urlConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"), 8);
String result = reader.readLine();
return result;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
Here's an example of what postman is sending in their headers
It seems like your problem is here (see inline comments):
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(urlParameters);
// you wrote your URL parameters into Body
wr.flush();
wr.close();
//You closed your body and told server - you are done with request
conn.getOutputStream().write(postDataBytes);
// you wrote data into closed stream - server does not care about it anymore.
You have to append your urlParameters directly to the URL when you open it
Then you have to write your Form Data into body as you do:
conn.getOutputStream().write(postDataBytes);
and then close output stream

Send JSON data through POST in Java

I have this code to send JSON data (passed as a string) to the server (This code works when English characters are to be sent as values in dataJSON as far as I tested):
private static String sendPost(String url, String dataJSON) throws Exception {
System.out.println("Data to send: " + dataJSON);
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
String type = "application/json;charset=utf-8";
// add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Content-Length", String.valueOf(dataJSON.getBytes("UTF-8").length));
con.setRequestProperty("Content-Type", type);
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeUTF(dataJSON);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.print("Response string from POST: " + response.toString() + "\n");
return response.toString();
}
Problem is I don't get correct response, which I get for example using DHC Restlet Client.
The problem is I think the dataJSON must be encoded in UTF8. That's how the server expects it most likely.
But it seems I have some problem in code the way I try to convert it and send it.
Can someone help me send data in body as UTF8 string in above example?
I think I solved with this approach:
private static String sendPost2(String urlStr, String dataJSON) throws Exception {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
OutputStream os = conn.getOutputStream();
os.write(dataJSON.getBytes("UTF-8"));
os.close();
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
String result = new BufferedReader(new InputStreamReader(in)) .lines().collect(Collectors.joining("\n"));
in.close();
conn.disconnect();
return result;
}
Please suggest alternative if you see problem with it.

HttpURLConnection "An unexpected error occurred."

From my little knowledge of 500 errors I understand it is a server error. But what could be the root cause behind something like this? Could it be on my end?
The error i'm getting is:
{"status":500,"error":"An unexpected error occurred."}
Could it have to do with my headers i.e missing one? From what i've found from testing the error changes from 400 errors i.e 401 after adding the user agent header.
my code looks as follows:
String url="https://api.gotinder.com/auth";
URL object=new URL(url);
HttpURLConnection con = (HttpURLConnection) object.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Host", "host url");
//con.setRequestProperty("content-Length" , "287");
con.setRequestProperty("User-Agent" , "Tinder/4.0.4");
con.setRequestProperty("facebook_token", "token");
//con.setRequestProperty("facebook_id", "id");
System.out.println(con.getResponseCode());
Side note: This is all for educational purpose. I got intrigued.
The problem was I was passing my token as a Property and not a part of the body.
code:
String urlstr = "https://api.gotinder.com/auth";
String params = "facebook_token=" + this.fb_token;
URL url = new URL(urlstr);
HttpURLConnection urlconn = (HttpURLConnection) url.openConnection();
urlconn.setDoInput(true);
urlconn.setDoOutput(true);
urlconn.setRequestMethod("POST");
urlconn.setRequestProperty("User-Agent", "Tinder/3.0.4 (iPhone; iOS 7.1; Scale/2.00)");
urlconn.setRequestProperty("Content-Language", "en-US");
OutputStream os = urlconn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(params);
writer.close();
os.close();
if (urlconn.getResponseCode() == 200) {
BufferedReader bR = new BufferedReader(new InputStreamReader(urlconn.getInputStream()));
String line = "";
StringBuilder responseStrBuilder = new StringBuilder();
while ((line = bR.readLine()) != null) {
responseStrBuilder.append(line);
}
urlconn.getInputStream().close();
JSONObject result = new JSONObject(responseStrBuilder.toString());
user_token = result.getString("token");
System.out.println("User token is: " + user_token);
} else {
System.out.println("Want to print error here had getting data...");
}

Categories