I am making something for my HipChat room but for it to work i have to send a JSON request of:
POST /v1/rooms/message?format=json&auth_token=token HTTP/1.1
Host: api.hipchat.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 138
room_id=10&from=Alerts&message=A+new+user+signed+up
So far i have this:
public static void send(String send){
URL url = null;
HttpURLConnection conn = null;
try{
url = new URL("http://api.hipchat.com");
conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", "138");
conn.setUseCaches (false);
conn.setDoInput(true);
conn.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(
conn.getOutputStream ());
wr.writeBytes (send);
wr.flush ();
wr.close ();
InputStream is = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
System.out.println(line);
}catch(Exception e){
e.printStackTrace();
}finally{
if(conn != null) {
conn.disconnect();
}
}
}
But in the console it just returns null. How would i go about sending the above JSON request?
Thanks
Every time you loop here
while((line = rd.readLine()) != null) {
your line variable is replaced with the value returned by rd.readLine(). The last time it loops, that method call will return null. That's why line is null.
I'm going to assume you wanted to print out response.
Related
process an https page sending its parameters
Java8u201 using HttpsURLConnection
String httpsURL = "https://www.wmtechnology.org/Consultar-RUC/";
URL myUrl = null;
String[][] parameter = { { "modo", "1" }, { "btnBuscar", "Buscar" }, { "nruc", "10460332759" } };
System.out.println(parameter.toString());
try {
myUrl = new URL(httpsURL);
HttpsURLConnection conn = (HttpsURLConnection) myUrl.openConnection();
conn.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(parameter.toString());
wr.flush();
wr.close();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = br.readLine()) != null) {
System.out.println(inputLine);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
returns the page but without data
Consider using a library which handles the underlying connection/request for you. The Apache HTTP Client has a fluent API which would make the code easier to write:
String result = Request
.Post("https://www.wmtechnology.org/Consultar-RUC/")
.bodyForm(Form
.form()
.add("modo", "1")
.add("btnBuscar", "Buscar")
.add("nruc", "10460332759")
.build())
.execute()
.returnContent()
.asString();
System.out.println(result);
More information here: https://hc.apache.org/httpcomponents-client-4.2.x/tutorial/html/fluent.html
This request does return data.
You are wrong on the line
wr.writeBytes(parameter.toString());
because parameter.toString() returns string like [[Ljava.lang.String;#1f554b06 instead of expected param1=value1¶m2=value2 etc.
So correct this part to
String parameterString = Arrays.stream(parameter)
.map(pair -> pair[0] + "=" + pair[1])
.collect(Collectors.joining("&"));
wr.writeBytes(parameter.toString());
I would like to obtain the response from a HttpsURLConnection POST request.
If I try to do the request with PostMan, I have one message as response (es: 1520). I have to save this code, but I find the method for read just the getResponseCode() (200) or getResponseMessage() ("OK"). I should use another libraries? Because in the HttpsUrlConnection method I don't find anything useful (https://docs.oracle.com/javase/7/docs/api/java/net/HttpURLConnection.html)
My code is:
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setSSLSocketFactory(sslContext.getSocketFactory());
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestMethod("POST");
con.setRequestProperty("Connection", "keep-alive");
con.setRequestProperty("Content-Type", w_AECONTYP);
con.setRequestProperty("Accept-Charset", w_AEACCCHA);
con.setRequestProperty("Accept-Encoding", w_AEACCENC);
StringBuilder postFile = new StringBuilder();
byte[] postFileBytes =w_FileToSend.getBytes("UTF-8");
con.setDoOutput(true);
try {
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.write(postFileBytes);
wr.flush();
wr.close();
} catch (Exception e) {
System.out.println("Connection Failed");
e.printStackTrace();
}
int responseCode = con.getResponseCode();
// get 200 code "OK"
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
But when arrived at the WHILE loop, it doesn't enter in the cycle.
How I can do this?
The file is in JSON format, but that isn't the problem.
I need to save that 915 code!!
You could use HttpResponse and HttpPost for getting a response from server (as well as the Response Code):
HttpResponse httpResponse = httpClient.execute(new HttpPost(URL));
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
// now response is in the stringBuilder.toString()
I hope this will help you.
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 have following code. When i get the response, it's characters are faulty. i want to get the response with "UTF-8". How and where can i write that in my code below?
Thanks
URL httpPost = new URL(url);
HttpsURLConnection connection = (HttpsURLConnection) httpPost.openConnection();
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.getOutputStream().write(params.getBytes(Charset.forName("UTF-8")));
connection.getOutputStream().flush();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
try {
String responseFromServer = response.toString();
dealsResponse = Utils.mapper.readValue(responseFromServer, GetDealsResponse.class);
} finally {
in.close();
}
connection.setRequestProperty("Accept-Charset", "UTF-8");