I have tried every single question about it in here, but my code still returning 400, for every request that I try to do and I'm not getting what I'm doing wrong.
HttpURLConnection connection = null;
InputStream in = null;
try {
URL url = new URL(uri);
connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(10000);
connection.setConnectTimeout(20000);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
connection.setDoInput(true);
connection.setDoOutput(true);
String query = "";
if (Validator.isNotNull(paramsMap) && !paramsMap.isEmpty()) {
Uri.Builder builder = new Uri.Builder();
for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
builder.appendQueryParameter(entry.getKey(), entry.getValue());
}
query = builder.build().getEncodedQuery();
}
if (!query.isEmpty()) {
OutputStream os = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
}
connection.connect();
int status = connection.getResponseCode();
if (status == 200) {
in = connection.getInputStream();
} else {
in = connection.getErrorStream();
}
} finally {
connection.disconnect();
}
return in;
I would try to get it working using a separate tool (there are quite a few browser plugins that let you create POST requests (Postman, HttpRequester, etc.) Use one of those to figure out exactly what you need to POST to get it to work. Once you have it working in one of the tools, you can do the same thing in your Java code.
Related
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.
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...");
}
I am calling REST service using java HttpURLConnection object.
When the HTTP server returns any business error, I am not able to retrieve the error properly.
For example, when I call the REST service through SoapUI, I get below error
<exception>
<errors>
<error>
<diagnostic>Matching item with shortCode = 1089992001234 found</diagnostic>
<field>shortCode</field>
<message>The Shortcode/CSG combination must be unique.</message>
<objectFailingValidationClass>com.axiossystems.assyst.dto.organisationConfiguration.SectionDto</objectFailingValidationClass>
<rule>isUniqueShortCodeWithCSG</rule>
</error>
</errors>
<message>A complex validation error has been detected by the application.</message>
<type>ComplexValidationException</type>
</exception>
But in the java code I getting below error, the request message format is correct
java.io.IOException: Server returned HTTP response code: 400 for URL: https://it-test.ihc.eu/assystREST/v2/sections
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at sun.net.www.protocol.http.HttpURLConnection$6.run(HttpURLConnection.java:1676)
at sun.net.www.protocol.http.HttpURLConnection$6.run(HttpURLConnection.java:1674)
at java.security.AccessController.doPrivileged(Native Method)
at sun.net.www.protocol.http.HttpURLConnection.getChainedException(HttpURLConnection.java:1672)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1245)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
at RestCaller.execute(RestCaller.java:59)
at RestCaller.main(RestCaller.java:18)
Can anyone let me know how to capture business error returned form server? Like the one received in SoapUI
Below is my code
try
{
url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("accept", "application/xml");
String userpassword = username + ":" + password;
String authStringEnc = new String(Base64.encodeBase64(userpassword.getBytes()));
connection.setRequestProperty("Authorization", "Basic "+authStringEnc);
if (HttpMethod == "POST")
{
connection.setRequestMethod("POST");
//connection.setRequestProperty("Content-Length","" + Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Type", "application/xml");
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
OutputStream os = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(payLoad);
writer.flush();
writer.close();
os.close();
}
int statusCode = connection.getResponseCode();
System.out.println("--------000----------" + statusCode);
InputStream is = connection.getInputStream();
System.out.println("--------111----------");
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
System.out.println("--------222----------");
String line;
System.out.println("--------333----------");
StringBuffer response = new StringBuffer();
System.out.println("--------444----------");
while ((line = rd.readLine()) != null)
{
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
}
catch (Exception e)
{
System.out.println("--------exception----------");
e.printStackTrace();
return "";
}
In case of error (i.e., httpStatusCode other than 200), you might have to read errorStream of HttpUrlConnection as below. After you read errorMessage, you could to deserialize it to the DTO that matches the xml output you pasted. Please note readErrorString() below is incomplete and expect you to use it for reference only
if (statusCode != 200) {
InputStream errorStream = connection.getErrorStream();
String errorMessage = (errorStream != null) ? readErrorString(errorStream) : connection
.getResponseMessage();
}
private void readErrorString(InputStream is) {
String responseString = null;
BufferedInputStream bis = null;
try {
StringBuilder sb = new StringBuilder();
bis = new BufferedInputStream(inputStream);
byte[] byteContents = new byte[4096];
int bytesRead;
String strContents;
while ((bytesRead = bis.read(byteContents)) != -1) {
strContents = new String(byteContents, 0, bytesRead, "UTF-8"); // You might need to replace the charSet as per the responseEncoding returned by httpurlconnection above
sb.append(strContents);
}
responseString = sb.toString();
} finally {
if (bis != null) {
bis.close();
}
}
}
return responseString;
400 error means your response data is malformed, means not in correct format. Please check again with your response api.
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}");
I use HttpUrlConnection to post outside a json but seems Chinese characters are changing to ?????
I tried with different encoding style like utf-16,big 5 but I cant understand what is causing this.
When I debug this, I can see chineese character before post, but when post, it changes why?
code parts is in the below
String postData,String charset) throws MalformedURLException, IOException{
URL url = new URL(targetUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection(
Proxy.NO_PROXY);
connection.setConnectTimeout(postTimeout);
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
contentType+"; charset="+charset);//+charset.getName().toUpperCase());//+charset.getName());
sleep(sleepTime);
OutputStream os = connection.getOutputStream();
//"UnicodeBigUnmarked"
//
// byte[] bt= postData.getBytes();
// System.out.println(bt);
// os.write(bt);
// System.out.println();
// os.flush();
//System.out.println(postData);
try
{
Writer writer = new OutputStreamWriter(os, charset);
writer.write(postData);
writer.flush();
writer.close();
} catch (IOException e) {
logger.severe("Http POST exception");
} finally {
if (os != null) {
os.close();
}
}
int responseCode = connection.getResponseCode();
connection.disconnect();
return responseCode;
I tried with big5,utf-16, but still no change.
Thanks.
I believe that you should use the unicode ascii-safe representation in JSon like explained here