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...");
}
Related
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));
}
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.
I'm trying to use glot.io api to compile java code with curl.
I read a text file :
BufferedReader bufferedReader = new BufferedReader(new FileReader("input.txt"));
StringBuffer stringBuffer = new StringBuffer();
String line = bufferedReader.readLine();
while(line != null){
stringBuffer.append(line);
line = bufferedReader.readLine();
}
If I use no quotation marks, I have no problem when I request the url
URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty ("Authorization", "Token myToken");
conn.setRequestProperty("Content-Type", "application/json");
String data = "{\"files\": [{\"name\": \"main.java\", \"content\": \"" + stringBuffer.toString() + "\"}]}";
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
out.write(data);
out.close();
BufferedReader bf = new BufferedReader(new InputStreamReader(conn.getInputStream()));
System.out.println(bf.readLine());
But when I use String in my code, the web page return 400 error.
Can you help me ?
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.
I have to pass a token as part of validation for each GET request to access RESTful web service. Below is the code I'm using it to access REST api:
public static String httpGet(String urlStr, String[] paramName, String[] paramVal) throws Exception {
URL url = new URL(urlStr);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStream out = conn.getOutputStream();
Writer writer = new OutputStreamWriter(out, "UTF-8");
for (int i = 0; i < paramName.length; i++) {
writer.write(paramName[i]);
writer.write("=");
writer.write(URLEncoder.encode(paramVal[i], "UTF-8"));
writer.write("&");
}
writer.close();
out.close();
if (conn.getResponseCode() != 200) {
System.out.println("Response code: "+conn.getResponseCode());
throw new IOException(conn.getResponseMessage());
}
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
conn.disconnect();
return sb.toString();
}
I can't see any such method to set Header conn.setHeader() provided for HttpsURLConnection. It should be something like X-Cookie: token={token}; please help me to find a way to set header.
You can use:
conn.addRequestProperty("X-Cookie", "token={token}");
or setRequestProperty() also works
You are already setting headers on your request in your code when you do the following:
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
I.e. if the service you are communicating with requires that you send your token in the "X-Cookie" header you can simply do the same for that header:
conn.setRequestProperty("X-Cookie", "token={token}");