I need to send many requests one by one. I have a code:
public void sendRestRequest(String xmlFile){
try{
String myRequest = generateStringFromResource(xmlFile);
given().auth().basic(prop.getProperty("restLogin"), prop.getProperty("restPassword"))
.contentType("application/xml")
.body(myRequest.getBytes(StandardCharsets.UTF_8))
.when()
.post(prop.getProperty("restURL"))
.then().
assertThat().statusCode(200).and().
assertThat().body("status", equalTo("UPLOADED"));
}
catch (Exception e){ LOG.error(String.valueOf(e)); }
}
public static String generateStringFromResource(String path) throws IOException {
return new String(Files.readAllBytes(Paths.get(path)));
}
I can successfully create first request. But in the second one I have 500 status code instead of 200. And such error message:
at io.restassured.internal.ResponseSpecificationImpl$HamcrestAssertionClosure.validate(ResponseSpecificationImpl.groovy:483)
at io.restassured.internal.ResponseSpecificationImpl$HamcrestAssertionClosure$validate$1.call(Unknown Source)
at io.restassured.internal.ResponseSpecificationImpl.validateResponseIfRequired(ResponseSpecificationImpl.groovy:655)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:210)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:59)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:166)
at io.restassured.internal.ResponseSpecificationImpl.statusCode(ResponseSpecificationImpl.groovy:123)
at io.restassured.specification.ResponseSpecification$statusCode$0.callCurrent(Unknown Source)
at io.restassured.internal.ResponseSpecificationImpl.statusCode(ResponseSpecificationImpl.groovy:131)
at io.restassured.internal.ValidatableResponseOptionsImpl.statusCode(ValidatableResponseOptionsImpl.java:119)
May be anybody has ideas? I guess that should be some connection closer or something like this.
On the server side the problem was with xml file, but it is strange, because there are no problems with the same file if I send it first time. After some attempts, I decided to use different approach which works great:
public void sendRestRequest(String xmlFile) throws IOException {
FileInputStream fis = new FileInputStream("configuration.properties");
prop.load(fis);
try {
URL url = new URL(prop.getProperty("restURL"));
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/xml");
conn.setRequestProperty("Authorization", prop.getProperty("basic"));
String input = generateStringFromResource(xmlFile);
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
StringBuilder responseStrBuilder = new StringBuilder();
String output;
while ((output = br.readLine()) != null) {responseStrBuilder.append(output);}
conn.disconnect();
JSONObject result = new JSONObject(responseStrBuilder.toString());
Assert.assertEquals(result.getString("status"), "UPLOADED");
} catch (IOException e) {
LOG.error(String.valueOf(e));
}
}
Related
I am trying to call an API that gives 400 on some requests.
But it has meaningful message that needs to be read.
Also i am passing a payload(json body) in the api call
My code(it takes a payload as json) and the 400 response is below
I am able to successfully read the response of 200 but issue is with 400
public static void blahblah (String input, String CustomerID, String endpoint, String dateNameFolder) throws UnknownHostException
{
try {
URL url = new URL(endpoint);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
StringBuilder sb = new StringBuilder();
String output;
while ((output = br.readLine()) != null) {
sb.append(output);
}
File fileObj = new File(CustomerID + ".json");
if (!fileObj.exists()) {
fileObj.createNewFile();
FileWriter dataWriter = new FileWriter(CustomerID + ".json");
dataWriter.write(sb.toString());
dataWriter.close();
} else {
FileWriter dataWriter = new FileWriter(CustomerID + ".json");
dataWriter.write(sb.toString());
dataWriter.close();
}
conn.disconnect();
}catch (MalformedURLException e) {
l
log.info(e);
}
catch (IOException e) {
log.error("Error in Validating Request to Catalog for Customer ID(400 Bad Request) : " + CustomerID ) ;
log.info(e);
}
}
Sample output of 400 bad request :
<Response>
<StatusCode>BadRequest</StatusCode>
<ErrorCode>OrderRequestInvalid.InvalidCharacteristicUse</ErrorCode>
<Message>Characteristic ID cannot be found in the specification: { EntityUniqueCode: CS_0aefdfec-022e-4ac9-a84b-83c8ea2e0fd0, CharacteristicID: 76c4e767-ce7b-4675-a178-d832839b322f}</Message>
<Context>
<EntityUniqueCode>CS_0aefdfec-022e-4ac9-a84b-83c8ea2e0fd0</EntityUniqueCode>
<CharacteristicID>76c4e767-ce7b-4675-a178-d832839b322f</CharacteristicID>
</Context>
</Response>
You need to choose correct stream depending on your response status. here is an example how you can do this:
BufferedReader br = null;
int statusCode = conn.getResponseCode();
if (statusCode>299){
br = new BufferedReared(new InputStreamReader(conn.getErrorStream()));
} else {
br = new BufferedReared(new InputStreamReader(conn.getInputStream()));
}
I am trying to retrieve users information from Azure active directory using Microsoft Graph api from java code but i am getting 400 error(Bad request) , but it works well in postman .
The java code with which i am working is
String url = "https://graph.microsoft.com/v1.0/users?$filter=displayName eq 'Dasari Siri'";
String token = "Bearer "+accesstoken;
URL obj = new URL(url);
HttpURLConnection con =(HttpURLConnection)obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Authorization", token);
con.connect();
StringBuffer Response = new StringBuffer();
if(con!=null){
try {
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); String input ;
while ((input = br.readLine()) != null){
Response.append(input);
}
br.close();
}
catch (IOException e) {
e.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}
}
The error which I am getting is
java.io.IOException: Server returned HTTP response code: 400 for URL: https://graph.microsoft.com/v1.0/users?$filter=displayName eq 'Dasari Siri'
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
at com.javatpoint.Downloadcsv.doDownloadCsv(Downloadcsv.java:80)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
The postman request which worked fine for me is :
Can you please go through this and let me know where i am making mistake
Thank you in advance
You need to do the encode for the filter part of the url and add a line to set property "Accept" as "application/json"). Please refer to my code below:
public class Testgraph {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
String url = "https://graph.microsoft.com/v1.0/users?" + URLEncoder.encode("$filter=displayName eq 'huryTest'", "UTF-8");
String token = "Bearer " + "your access token";
URL obj = new URL(url);
HttpURLConnection con =(HttpURLConnection)obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Authorization", token);
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Content-Type", "application/json");
int responseCode = con.getResponseCode();
StringBuffer Response = new StringBuffer();
if(con!=null){
try {
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
String input ;
while ((input = br.readLine()) != null){
Response.append(input);
System.out.print("---------success------");
}
br.close();
}
catch (IOException e) {
e.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}
}
}
}
My soap API is running on localHost. It is working fine when i access it from the browser or soap UI. But it throws 500 error when I access it from my java client
I tried to debug the code, but could not find anything. The server logs as well does not print anything. Only the tomcat access logs show the response code for the request
public class PostSoapRequest {
String soapEndpointUrl = "http://10.142.240.103:8082/notification-adaptor/services/ChangeTrigger";
public void postRequest(ChangeDeviceTrigger_Element changeDeviceTrigger) {
try {
URL obj = new URL(soapEndpointUrl);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
con.setRequestProperty("SOAPAction", "http://dpa.nokia.com/ChangeDeviceTrigger/");
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("User-Agent","Apache-HttpClient/4.1.1");
String xml = RequestXml.getXmlRequest();
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(xml);
wr.flush();
wr.close();
String responseStatus = con.getResponseMessage();
System.out.println("responseStatus :" + responseStatus);
System.out.println("getResponseCode :" + con.getResponseCode());
BufferedReader reader = null;
if (con.getResponseCode() == 200) {
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = reader.readLine()) != null) {
response.append(inputLine);
}
reader.close();
System.out.println("response:" + response.toString());
}else {
reader = new BufferedReader(new InputStreamReader(con.getErrorStream()));
}
System.out.println(reader.read());
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.println("response:" + response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
exception:
java.io.IOException: Server returned HTTP response code: 500 for URL: http://10.142.240.103:8082/notification-adaptor/services/ChangeTrigger
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorI mpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at sun.net.www.protocol.http.HttpURLConnection$10.run(HttpURLConnection.java:1944)
at sun.net.www.protocol.http.HttpURLConnection$10.run(HttpURLConnection.java:1939)
at java.security.AccessController.doPrivileged(Native Method)
at sun.net.www.protocol.http.HttpURLConnection.getChainedException(HttpURLConnection.java:1938)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1508)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492)
at com.nokia.dpa.ChangeDeviceTrigger.post.PostSoapRequest.postRequest(PostSoapRequest.java:49)
at com.nokia.dpa.ChangeDeviceTrigger.post.PostSoapRequest.main(PostSoapRequest.java:65)
Caused by: java.io.IOException: Server returned HTTP response code: 500 for URL: http://10.142.240.103:8082/notification-adaptor/services/ChangeTrigger
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1894)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480)
at java.net.HttpURLConnection.getResponseMessage(HttpURLConnection.java:546)
at com.nokia.dpa.ChangeDeviceTrigger.post.PostSoapRequest.postRequest(PostSoapRequest.java:30)
I found the soap request xml that was posted to the service endpoint was wrong. There was an extra "\" character in the request. The issue is not fixed
I have written a code for my swing application to login, i'm supposed to get flag as response from the web service as json format, the trouble I'm facing is that when I post the data I'm getting bad 400 request if I set the certain headers or 500 internal server error if the headers are not set.
Connection Class
public class Connection extends Thread {
private String url1;
private JSONObject data;
String line;
//Constuctor to initialize the variables.
public Connection(String url1, JSONObject data) {
this.url1 = url1;
this.data = data;
start();
}
public void run() {
ConnectionReaderWriter();
}
//To fetch the data from the input stream
public String getResult() {
return line;
}
public String ConnectionReaderWriter() {
URL url;
HttpURLConnection connection = null;
ObjectOutputStream out;
try {
/*URL url = new URL(Url.server_url + url1); //Creating the URL.
URLConnection conn = url.openConnection(); //Opening the connection.
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data); //Posting the data to the ouput stream.
wr.flush();
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
line=rd.readLine(); //Reading the data from the input stream.
wr.close();
rd.close();*/
url = new URL(Url.server_url + url1); //Creating the URL.
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
// Headers
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
// API key has to be passed
connection.setRequestProperty("api_key", "123456");
connection.setUseCaches(false);
//System.out.println(connection.getRequestProperty("api_key"));
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
out = new ObjectOutputStream(connection.getOutputStream());
out.write(data.toString().getBytes());
out.flush();
System.out.println(data.toString());
int rescode = connection.getResponseCode();
line = connection.getResponseMessage();
System.out.println(line +" : "+ rescode);
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
line = rd.readLine(); //Reading the data from the input stream.
rd.close();
out.close();
System.out.println("fsgjv: ");
} catch (MalformedURLException ex) {
Logger.getLogger(Connection.class.getName()).log(Level.SEVERE, null, ex);
String nonet = "No Network Connection";
line = nonet;
} catch (IOException ex) {
Logger.getLogger(Connection.class.getName()).log(Level.SEVERE, null, ex);
String nonet = "No Server Connection";
line = nonet;
}
return line; //Return te stream recived from the input stream.
}
}
The error generated is given below.
{"username":"ann.jake#gmail.com","password":"123"}
Bad Request : 400
Jan 20, 2014 6:00:04 PM SupportingClass.Connection ConnectionReaderWriter
SEVERE: null
java.io.IOException: Server returned HTTP response code: 400 for URL: http://192.168.10.241/MobpazAdmin/web/app_dev.php/ws/terminalusers/terminaluserlogins.json
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:525)
at sun.net.www.protocol.http.HttpURLConnection$6.run(HttpURLConnection.java:1674)
at sun.net.www.protocol.http.HttpURLConnection$6.run(HttpURLConnection.java:1672)
at java.security.AccessController.doPrivileged(Native Method)
at sun.net.www.protocol.http.HttpURLConnection.getChainedException(HttpURLConnection.java:1670)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1243)
at SupportingClass.Connection.ConnectionReaderWriter(Connection.java:81)
at SupportingClass.Connection.run(Connection.java:40)
Caused by: java.io.IOException: Server returned HTTP response code: 400 for URL: http://192.168.10.241/MobpazAdmin/web/app_dev.php/ws/terminalusers/terminaluserlogins.json
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1625)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:468)
at SupportingClass.Connection.ConnectionReaderWriter(Connection.java:78)
... 1 more
Please tell me if i have made any mistake in the code, I have checked the server side code it is working properly. the data that is to be passed is json object given below
{"username":"ann.jake#gmail.com","password":"123"}
The problem has to be coming from the server because it is returning a status code 400. Can you check the server logs to find any more info?
I change this method of access now i'm using a Httpget to achieve same. You have to download the corresponding httpcomponents-client jar file and add it to the library. The code to use is given below
data = URLEncoder.encode("searchvariable", "UTF-8") + "=" + URLEncoder.encode("name", "UTF-8");
HttpGet g = new HttpGet(Url.server_url + url1+"?"+data);
Data is the parameters to be passed along with the URL. The issue happened due to the wrong method of access.
Please tell me some one, How to resolve this problem,
Sometime I am getting Filenotfound Exception and Some time this code working fine.
Below is my code,
public String sendSMS(String data, String url1) {
URL url;
String status = "Somthing wrong ";
try {
url = new URL(url1);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");
conn.setRequestProperty("Accept","*/*");
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String s;
while ((s = rd.readLine()) != null) {
status = s;
}
rd.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
wr.close();
} catch (MalformedURLException e) {
status = "MalformedURLException Exception in sendSMS";
e.printStackTrace();
} catch (IOException e) {
status = "IO Exception in sendSMS";
e.printStackTrace();
}
return status;
}
Rewrite like this and let me know how you go... (note closing of reading and writing streams, also the cleanup of streams if an exception is thrown).
public String sendSMS(String data, String url1) {
URL url;
OutputStreamWriter wr = null;
BufferedReader rd = null;
String status = "Somthing wrong ";
try {
url = new URL(url1);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");
conn.setRequestProperty("Accept","*/*");
wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
wr.close();
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String s;
while ((s = rd.readLine()) != null) {
status = s;
}
rd.close();
} catch (Exception e) {
if (wr != null) try { wr.close(); } catch (Exception x) {/*cleanup*/}
if (rd != null) try { rd.close(); } catch (Exception x) {/*cleanup*/}
e.printStackTrace();
}
return status;
}
This issue seems to be known, but for different reasons so its not clear why this happend.
Some threads would recommend closing the OutputStreamWriter as flushing it is not enough, therefor i would try to clos it directly after fushing as you are not using it in the code between the flush and close.
Other threads show that using a different connections like HttpURLConnection are avoiding this problem from occuring (Take a look here)
Another article suggests to use the URLEncoder class’ static method encode. This method takes a string and encodes it to a string that is ok to put in a URL.
Some similar questions:
URL is accessable with browser but still FileNotFoundException with URLConnection
URLConnection FileNotFoundException for non-standard HTTP port sources
URLConnection throwing FileNotFoundException
Wish you good luck.
It returns FileNotFoundException when the server response to HTTP request is code 404.
Check your URL.