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.
Related
I'm currently working on a project using an IoT platform " Thingsboard " where I've have created multiple devices, and I want to send data to each one of the devices from a JSON File, I'm using Rest Api to perform this request, but I've struggling for a while how to get the access token of my devices and parse each one of them in my request as a header param. I was just doing manually by getting them with Curl, but I want now to do it automatically. I know that Thingsboard has a Rest client Api written in java (https://thingsboard.io/docs/reference/rest-client/) so I've tried to use that in my script but I's not working. I'm new to working with Rest Api so if anybody can gie me a clue it would be so helpful.
here's a part of my code for the requests :
private static String token;
public String getToken() {
return token;
}
String paramValue = "param\\with\\backslash";
String yourURLStr = "http://host.com?param=" + java.net.URLEncoder.encode(paramValue, "UTF-8");
URL url2 = new URL("https://demo.thingsboard.io/api/v1/token/telemetry?token=$JWT_TOKEN");
HttpsURLConnection conn = (HttpsURLConnection) url2.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty(JWT_TOKEN_HEADER_PARAM, "Bearer" +token);
conn.setDoOutput(true);
OutputStream outStream = conn.getOutputStream();
OutputStreamWriter outStreamWriter = new OutputStreamWriter(outStream, "UTF-8");
outStreamWriter.write(list.toString());
outStreamWriter.flush();
outStreamWriter.close();
outStream.close();
String response = null;
System.out.println(conn.getResponseCode());
System.out.println(conn.getResponseMessage());
DataInputStream input1 = null;
input1 = new DataInputStream (conn.getInputStream());
while (null != ((response = input1.readLine()))) {
System.out.println(response);
input1.close ();
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
If you are trying to get the JWT-token to authenticate the following java should work:
Request request = Request.Post("http://THINGSBOARD_URL/api/auth/login");
String body = "{\"username\":\"tenant#thingsboard.org\", \"password\":\"tenant\"}";
request.bodyString(body,ContentType.APPLICATION_JSON);
request.setHeader("Content-Type", "application/json");
request.setHeader("Accept", "application/json");
HttpResponse httpResponse = request.execute().returnResponse();
System.out.println(httpResponse.getStatusLine());
if (httpResponse.getEntity() != null) {
String html = EntityUtils.toString(httpResponse.getEntity());
System.out.println(html);
}
Don't get confused with JWT-Token for tenant authentication and Access-Token for Device Authentication.
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
Kindly don't confuse my question with sending body with POST request using HttpURLConnection.
I want to send body with GET request using HttpURLConnection. Here is code i am using.
public static String makeGETRequest(String endpoint, String encodedBody) {
String responseJSON = null;
URL url;
HttpURLConnection connection;
try {
url = new URL(endpoint);
connection = (HttpURLConnection) url.openConnection();
connection.setInstanceFollowRedirects(true);
connection.setDoOutput(true);
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.connect();
OutputStream outputStream = connection.getOutputStream();
outputStream.write(encodedBody.getBytes());
outputStream.flush();
Util.log(connection,connection.getResponseCode()+":"+connection.getRequestMethod());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String responseChunk = null;
responseJSON = "";
while ((responseChunk = bufferedReader.readLine()) != null) {
responseJSON += responseChunk;
}
bufferedReader.close();
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
Util.log(e, e.getMessage());
}
return responseJSON;
}
what happens is that the request type is identified automatically depending on the connection.getInputStream() and connection.getOutPutStream().
when you call connection.getOutPutStream() the request type is automatically set to POST even if you have explicitly set request type to GET using connection.setRequestMethod("GET").
The problem is that i am using 3rd party Web Service(API) which accepts request parameters as body with GET request
<get-request>
/myAPIEndPoint
body = parameter1=value as application/x-www-form-urlencoded
<response>
{json}
I am well aware that most of the case GET don't have request body but many of the web service often uses GET request with parameters as body instead of query string. Kindly guide me how i can send GET request with body in android without using any 3rd party library(OkHttp,Retrofit,Glide etc)
use this code you will need to do a little modification but it will get the job done.
package com.kundan.test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
public class GetWithBody {
public static final String TYPE = "GET ";
public static final String HTTP_VERSION = " HTTP/1.1";
public static final String LINE_END = "\r\n";
public static void main(String[] args) throws Exception {
Socket socket = new Socket("localhost", 8080); // hostname and port default is 80
OutputStream outputStream = socket.getOutputStream();
outputStream.write((TYPE + "<Resource Address>" + HTTP_VERSION + LINE_END).getBytes());//
outputStream.write(("User-Agent: Java Socket" + LINE_END).getBytes());
outputStream.write(("Content-Type: application/x-www-form-urlencoded" + LINE_END).getBytes());
outputStream.write(LINE_END.getBytes()); //end of headers
outputStream.write(("parameter1=value¶meter2=value2" + LINE_END).getBytes()); //body
outputStream.flush();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
StringBuilder builder = new StringBuilder();
String read = null;
while ((read = bufferedReader.readLine()) != null) {
builder.append(read);
}
String result = builder.toString();
System.out.println(result);
}
}
this the Raw HTTP Request Dump
GET <Resource Address> HTTP/1.1
User-Agent: Java Socket
Content-Type: application/x-www-form-urlencoded
parameter1=value¶meter2=value2
Note : This is for http request if you want https Connection Please refer to the link SSLSocketClient
I'm trying to access FCM from my server app. Checked the example provided into here! But getting error:
java.io.IOException: Server returned HTTP response code: 400 for URL: https://fcm.googleapis.com/v1/projects/unsaarmdm/messages:send
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1627)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
at asd.MessagesClientFCMServer.sendMessageToFcm(MessagesClientFCMServer.java:66)
at asd.MessagesClientFCMServer.sendData(MessagesClientFCMServer.java:40)
at asd.MessagesClientFCMServer.main(MessagesClientFCMServer.java:37)
I've already created the firebase project called "unsaarmdm" and downloaded the json file that contains the private key. Also added the Google API Client library into my project.
Below is the code snippets:
private static String FCM_DEALS_ENDPOINT
= "https://fcm.googleapis.com/v1/projects/unsaarmdm/messages:send";
//https://fcm.googleapis.com/v1/projects/unsaarmdm/messages:send
public static void main(String args[]) {
MessagesClientFCMServer fcmClient = new MessagesClientFCMServer();
fcmClient.sendData();
}
private void sendData(){
sendMessageToFcm(getFcmMessageJSONData());
}
//Using HttpURLConnection it send http post request containing data to FCM server
private void sendMessageToFcm(String postData) {
try {
HttpURLConnection httpConn = getConnection();
DataOutputStream wr = new DataOutputStream(httpConn.getOutputStream());
wr.writeBytes(postData);
wr.flush();
wr.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(httpConn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
log.info(response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
private static String getAccessToken() throws IOException {
GoogleCredential googleCredential = GoogleCredential
.fromStream(new FileInputStream("C:/dev/Firebase_private_key/unsaarmdm-firebase-adminsdk.json"))
.createScoped(Arrays.asList(SCOPE));
googleCredential.refreshToken();
String token = googleCredential.getAccessToken();
return token;
}
//create HttpURLConnection setting Authorization token
//and Content-Type header
private HttpURLConnection getConnection() throws Exception {
URL url = new URL(FCM_DEALS_ENDPOINT);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("Authorization", "Bearer " + getAccessToken());
httpURLConnection.setRequestProperty("Content-Type", "application/json; UTF-8");
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.connect();
return httpURLConnection;
}
The url looks more like https://fcm.googleapis.com/fcm/send
This is a weird part, I'm aware the docs say to use the URL you are using, but I have a working implementation (and I know I spent some time debbuging this) with the URL i just mentioned, try and let me know :) we all can learn.
Make sure you include the server key into the Authorization header (which it seems you are doing ok).
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));
}
}