After running the post request with JSON I have HTTP Error 400 Bad request.
I think the problem is in the JSON string but I do not now how to fix it.
package Curl;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.http.HttpRequest;
import java.nio.charset.StandardCharsets;
public class Http_Con {
private static HttpURLConnection connection;
public static void main(String[] args) throws IOException {
Http_Con connection = new Http_Con();
//call the getRequest method
connection.GetRequest();
//call the postRequest
connection.PostRequest();
}
public void GetRequest() {
BufferedReader reader;
String lines;
StringBuilder responseContent = new StringBuilder();
try {
//set the url
URL url = new URL("http://192.168.0.104:4041/iot/devices");
//open the connection
connection = (HttpURLConnection) url.openConnection();
//set the request method and timeout
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
//set request properties(in this case headers)
connection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Fiware-Service", " myHome");
connection.setRequestProperty("Fiware-ServicePath", "/environment");
//get the response code(200 should be OK)
int status = connection.getResponseCode();
if (status > 299) {
reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
while ((lines = reader.readLine()) != null) {
responseContent.append(lines);
}
reader.close();
} else {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((lines = reader.readLine()) != null) {
responseContent.append(lines);
}
reader.close();
}
//print the response content(result)
System.out.println(responseContent.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
public void PostRequest() throws IOException {
//set the url
String url = "http://192.168.0.104:4041/iot/devices";
URL obj = new URL(url);
//open the connection
HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
//set the method type(POST OR GET)
connection.setRequestMethod("POST");
//set hte request properties(headers etc.)
connection.setRequestProperty("Content-Type", "application/json; utf-8");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Fiware-Service"," myHome");
connection.setRequestProperty("Fiware-ServicePath","/environment");
//make sure that will be able to write content to the connection output stream
connection.setDoOutput(true);
//Json formatted input string
String jsonInputString = "{\n" +
" \"devices\": [\n" +
" {\n" +
" \"device_id\": \"sensor01\",\n" +
" \"entity_name\": \"LivingRoomSensor\",\n" +
" \"entity_type\": \"multiSensor\",\n" +
" \"attributes\": [\n" +
" { \"object_id\": \"t\", \"name\": \"Temperature\", \"type\": \"celsius\" },\n" +
" { \"object_id\": \"l\", \"name\": \"Luminosity\", \"type\": \"lumens\" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
"}";
try(OutputStream os = connection.getOutputStream()) {
byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
try(BufferedReader br = new BufferedReader(
new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
//print the result
System.out.println(response.toString());
}
}
}
I Think you can use Fidder application to do something, which find Questions so fast. Due to 400 statusCode, Liking Cookie lost, params lost, request method lost .... trust think for you help!
Related
I am creating a Java Rest api to create users on Google Duo admin. I am following the documentation https://duo.com/docs/adminapi and they need auth and date/time header. I am fairly new to java can anyone guide me?
This is the updated code which I with authentication and date/time header but now getting the below error.
UPDATED CODE
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
public class DuoAdminAPI {
public static void POSTRequest() throws IOException {
String userCredentials = "Username:Password";
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes()));
String dateTime = OffsetDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME); //RFC_1123 == RFC_2822
final String POST_PARAMS = "{\n" + "\"userId\": 101,\r\n" +
" \"id\": 101,\r\n" +
" \"title\": \"Test Title\",\r\n" +
" \"body\": \"Test Body\"" + "\n}";
System.out.println(POST_PARAMS);
URL obj = new URL("https://api-e9770554.duosecurity.com");
HttpURLConnection postConnection = (HttpURLConnection) obj.openConnection();
postConnection.setRequestMethod("POST");
postConnection.setRequestProperty("Content-Type", "application/json");
postConnection.setRequestProperty("Authorization", basicAuth);
postConnection.setRequestProperty("Date", dateTime);
postConnection.setDoOutput(true);
OutputStream os = postConnection.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
int responseCode = postConnection.getResponseCode();
System.out.println("POST Response Code : " + responseCode);
System.out.println("POST Response Message : " + postConnection.getResponseMessage());
if (responseCode == HttpURLConnection.HTTP_CREATED) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
postConnection.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 NOT WORKED");
}
}
}
ERROR
{
"code": 40101,
"message": "Missing request credentials",
"stat": "FAIL"
}
Response code: 401 (Unauthorized); Time: 2022ms; Content length: 73 bytes
As I have read the documentation, the authorization is Basic:
String userCredentials = "username:password";
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes()));
For date is this:
String dateTime = OffsetDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME); //RFC_1123 == RFC_2822
In their documentation they require RFC 2822 format. We already have declared RFC 1123 in DateTimeFormatter, which practically it is the same.
And this is the way you can add them in headers:
postConnection.setRequestProperty("Authorization", basicAuth);
postConnection.setRequestProperty("Date", dateTime);
I have been told to execute this java program which is linked to a virtual number, when you run it, the output is a number code or whatever it is that i sent the number in sms.
I am using selenium and maven and also in the eclipse program and was told to use the testng plugin. They asked me to use #test annotations in an .xml file to execute it.
Im knew to programming and to be honest i have no idea how to write the xml file in order to run this and when i ask the person who told me to do this all they do is say google it and i have tried but i havent found anything.
the code is:
package utility;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Assert;
import org.apache.commons.codec.binary.Base64;
//import sun.misc.BASE64Encoder;
public class APIcall {
// String MobileNo = ""; // virtual mobile no. (From message media)
private final String USER_AGENT = "Mozilla/5.0";
// Msg media Account:
// Password:
String name = ;
String password = ;
String authString = name + ":" + password;
//String authStringEnc = new BASE64Encoder().encode(authString.getBytes());
String authStringEnc = new Base64().encodeBase64String(authString.getBytes());
static String URL = "https://api.messagemedia.com";
String getURI = "/v1/replies";
static String postURI = "/v1/replies/confirmed";
static Client client = ClientBuilder.newClient();
public Data getRequest() {
Response response = (Response) client.target(URL +
getURI).request(MediaType.APPLICATION_JSON_TYPE)
.header("Authorization", "Basic " + authStringEnc).get();
String body = response.readEntity(String.class);
// System.out.println("status: " + response.getStatus());
// System.out.println("headers \n: " + response.getHeaders());
System.out.println("body: \n" + body);
JSONObject json = new JSONObject(body);
JSONArray reply = (JSONArray) json.get("replies");
List<String> ids = new ArrayList<String>();
for (int idx = 0; idx < reply.length(); idx++) {
// ids.add(replyIds.get(idx).toString());
ids.add(reply.getJSONObject(idx).getString("reply_id"));
}
Assert.assertEquals(200, response.getStatus());
/*
* String OTPcode = (String) body.substring(body.lastIndexOf(' ') + 1); OTPcode
* = OTPcode.substring(0, 6).trim();
*/
String getContent = reply.getJSONObject(0).getString("content");
System.out.println(getContent);
String[] content = getContent.split(" ");
String code = content[content.length - 1];
// System.out.println("OTP code : " + code);
// System.out.println("List of replies : " + ids);
return new Data(code, ids, getContent);
//JSONException
}
public final class Data {
public String otp;
public List<String> list;
public String getContent;
public Data(String otp, List list, String getContent) {
this.otp = otp;
this.list = list;
this.getContent = getContent;
}
}
public void postRequest() {
/*
* Post request : Add reply ids recieved from GET request and pass it in body
* with POST request to confirm replies
*/
List<String> ids = getRequest().list;
String postStr = "{ \"reply_ids\":[";
for (String id : ids) {
postStr += "\"" + id + "\", ";
}
postStr += " ]}";
StringBuilder postString = new StringBuilder(postStr);
postString.replace(postStr.lastIndexOf(","),
postStr.lastIndexOf(",") + 1, "");
postStr = postString.toString();
// System.out.println("Reply id list : " + postStr);
Response response = client.target(URL + postURI)
.request(MediaType.APPLICATION_JSON_TYPE)
.header("Accept", "application/json")
.header("Authorization", "Basic " +
authStringEnc).header("Content-Type",
"application/json").post(Entity.json(postStr));
/*
* System.out.println("status: " + response.getStatus());
* System.out.println("headers \n: " + response.getHeaders());
* System.out.println("body: \n" +
response.readEntity(String.class));
*/
}
private void sendGet() throws Exception {
String url = URL + getURI;
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
// add request header
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Authorization", "Basic " + authStringEnc);
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' 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();
// print result
System.out.println(response.toString());
}
private void sendPost() throws Exception {
String url = URL + postURI;
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
// add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
// con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Authorization", "Basic " + authStringEnc);
String urlParameters = "{\"reply_ids\":\"25ebbf01-5614-4ea6-a4f7-67b752d18ed2\",\"63ed8e18-ecf0-444d-b79e-341e944b0b94\"}";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
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();
// print result
System.out.println(response.toString());
}
public static void main(String[] args) throws Exception {
/*
* System.setProperty("http.proxyHost", "");
* System.setProperty("http.proxyPort", "");
*/
APIcall apiCall = new APIcall();
apiCall.getRequest();
apiCall.postRequest();
}
}
If I understand correctly, they want you to convert this into a TestNG test which shouldn't be too difficult as the test and methods are already built. Considering you don't know Java, nor programming, I suggest watching a couple of Youtube videos to get you up to speed on TestNG. I believe once you get your feet wet with TestNG, much of the code along with how to convert it will make more sense.
#Test annotation will behave like a void main for each test (which is a method with the #Test annotation).
You can add a dependency in your maven pom.xml file for junit or testng (any of them will bring this annotation), then, you can trigger the test by running the method from your IDE, or from command line you can simple use:
mvn clean test - to trigger all existent tests
mvn clean test -Dtest=your.package.TestClassName - to trigger tests from a class
mvn clean test -Dtest=your.package.TestClassName#particularMethod - to trigger a specific test
i tried to login gmail via sending post request flowwing the code:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package testautologingmail;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.HttpCookie;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class HttpUrlConnectionExample {
private static List<String> cookies = new ArrayList<>();;
private static HttpsURLConnection conn;
private final String USER_AGENT = "Mozilla/5.0";
public HttpUrlConnectionExample(){
}
public static void main(String[] args) throws Exception {
String url = "https://accounts.google.com/ServiceLoginAuth";
String gmail = "https://mail.google.com/mail/";
HttpUrlConnectionExample http = new HttpUrlConnectionExample();
// make sure cookies is turn on
//CookieHandler.setDefault(new CookieManager());
// 1. Send a "GET" request, so that you can extract the form's data.
String page = http.GetPageContent(url);
String postParams = http.getFormParams(page,"kiemtienol1506","vandai1507");
// 2. Construct above post's content and then send a POST request for
// authentication
http.sendPost(url, postParams);
// 3. success then go to gmail.
String result = http.GetPageContent(gmail);
System.out.println(result);
conn.disconnect();
}
private static void getcookies(String url) throws MalformedURLException, IOException{
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
URL obj = new URL(url);
conn = (HttpsURLConnection) obj.openConnection();
conn.getContent();
List<HttpCookie> cookies2 = cookieManager.getCookieStore().getCookies();
System.out.println("get cookies");
for (HttpCookie cookie : cookies2) {
System.out.println(cookie.getDomain());
System.out.println(cookie.toString());
String temp = cookie.toString();
cookies.add(temp);
}
//conn.disconnect();
}
private void sendPost(String url, String postParams) throws Exception {
URL obj = new URL(url);
conn = (HttpsURLConnection) obj.openConnection();
// Acts like a browser
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Host", "accounts.google.com");
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
System.out.println("cookies String");
for (String cookie : cookies) {
//String[] tmp = cookie.split(":");
conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
System.out.println(cookie.split(";", 1)[0]);
}
conn.setRequestProperty("Connection", "keep-alive");
conn.setRequestProperty("Referer", "https://accounts.google.com/ServiceLoginAuth");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", Integer.toString(postParams.length()));
conn.setDoOutput(true);
conn.setDoInput(true);
// Send post request
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(postParams);
wr.flush();
wr.close();
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + postParams);
System.out.println("Response Code : " + responseCode);
BufferedReader in =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//System.out.println(response.toString());
//conn.disconnect();
}
private String GetPageContent(String url) throws Exception {
URL obj = new URL(url);
conn = (HttpsURLConnection) obj.openConnection();
// default is GET
conn.setRequestMethod("GET");
conn.setUseCaches(false);
// act like a browser
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
if (cookies != null) {
for (String cookie : cookies) {
conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
}
}
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// Get the response cookies
//setCookies(conn.getHeaderFields().get("Set-Cookie"));
getcookies(url);
return response.toString();
}
public String getFormParams(String html, String username, String password)
throws UnsupportedEncodingException {
System.out.println("Extracting form's data...");
Document doc = Jsoup.parse(html);
// Google form id
Element loginform = doc.getElementById("gaia_loginform");
Elements inputElements = loginform.getElementsByTag("input");
List<String> paramList = new ArrayList<String>();
for (Element inputElement : inputElements) {
String key = inputElement.attr("name");
String value = inputElement.attr("value");
String id = inputElement.attr("id");
if (key.equals("Email"))
{
value = username;
paramList.add(key + "=" + URLEncoder.encode(value, "UTF-8"));
}
else if (key.equals("Passwd")){
paramList.add(key + "=" + URLEncoder.encode(value, "UTF-8"));
value = password;
}
else if(id.equals("Passwd-hidden")){
value = password;
paramList.add("Passwd=" + URLEncoder.encode(value, "UTF-8"));
}else
paramList.add(key + "=" + URLEncoder.encode(value, "UTF-8"));
}
// build parameters list
StringBuilder result = new StringBuilder();
for (String param : paramList) {
if (result.length() == 0) {
result.append(param);
} else {
result.append("&" + param);
}
}
return result.toString();
}
public List<String> getCookies() {
return cookies;
}
public void setCookies(List<String> cookies) {
this.cookies = cookies;
}
}
i also try to get cookies flow this line setCookies(conn.getHeaderFields().get("Set-Cookie")); but it's always return null String so i have to make getCookies() function.
i always receive status 200 OK. So is there any support to help me or another code can do this task.
Thanks in Advance.
I am currently working on a school project using android. I have java code that sends an HTTP request to a server. It works just find on my laptop using eclipse, but when I try it on my android tablet (an android trio using android 4.4), it does not work. Instead it returns an error (An error occurred while sending the request: in the catch). It is going by the try block and moving to the catch block.
I am attaching the code used for the HTTP request below. I will be leaving out the server information for security reasons. I know the code works, like I said It works on my desktop. Why won't it work with my tablet? Can someone give me a hand with this?
package com.example.tito.profile1;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import android.widget.Toast;
import com.google.gson.Gson;
public class GetUserTest
{
String userName;
public GetUserTest()
{
userName = "Before try";
GetUserRequest request = new GetUserRequest();
request.setSecurityString("Left out for security");
request.setUserId(1);
request.setUserIdToGet(1);
Gson gson = new Gson();
String data = gson.toJson(request);
try
{
URL urlObject = new URL("http://Left out for security");
HttpURLConnection connection = (HttpURLConnection) urlObject.openConnection();
//userName = connection.toString();
connection.setDoInput(true);
connection.setRequestProperty("Content-Type", "application/json");
connection.setConnectTimeout(120000);
connection.setReadTimeout(120000);
connection.setRequestMethod("POST");
connection.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
wr.write(data);
wr.flush();
wr.close();
if(connection.getResponseCode() == HttpURLConnection.HTTP_OK)
{
InputStream inputStream = connection.getInputStream();
BufferedReader reader = null;
String inputLine;
StringBuilder builder = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
while ((inputLine = reader.readLine()) != null)
{
builder.append(inputLine);
}
if (reader != null)
{
reader.close();
}
String result = builder.toString();
GetUserResponse response = gson.fromJson(result, GetUserResponse.class);
System.out.println(response.getMessage());
if (response.getSuccess() == true)
{
UserInfo user = response.getUser();
/*System.out.println("UserName: " + user.getUserName());
System.out.println("DisplayName: " + user.getDisplayName());
System.out.println("Description: " + user.getDescription());
System.out.println("Email: " + user.getEmail());
System.out.println("ProductCount: " + user.getProductCount());
System.out.println("FollowedUsers: " + user.getFollowedUsers());
System.out.println("FollowingUsers: " + user.getFollowingUsers());*/
//System.out.println("Join Date:" + user.getCreatedDate());
// userName = "in if statement";
// userName = user.getDisplayName();
}
}
else
{
userName = "error in after else";
//userName = "An error occurred while sending the request: " + connection.getResponseMessage();
}
}
catch (Exception ex)
{
ex.printStackTrace();
userName = "An error occurred while sending the request: in the catch ";
}
}
public String sendBack()
{
return userName;
}
}
I am developing API in java to get json from GoEuro API is available at github. i want to know parameter i need to send with POST method and get result as json and combined with my custom logic.
Here is my java code to call api.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class JsonEncodeDemo {
public static void main(String[] args) {
try {
URL url = new URL("http://www.goeuro.com/GoEuroAPI/rest/api/v3/search?departure_fk=318781&departure_date=16%2F04%2F2017&arrival_fk=380553&trip_type=one-way&adults=1&children=0&infants=0&from_filter=Coventry+%28COV%29%2C+United+Kingdom&to_filter=London%2C+United+Kingdom&travel_mode=bus&ab_test_enabled=");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
// conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()), "UTF-8"));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I am not good in nodejs. Any Help would be appreciated.
First of all the url needs to be only this http://www.goeuro.com/GoEuroAPI/rest/api/v3/search
Then you need to add parameters using params in request.
Your if response != 200 has to be after you make the request.
public static void main(String[] args) {
try {
URL url = new URL("http://www.goeuro.com/GoEuroAPI/rest/api/v3/search);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Accept", "application/json");
String urlParameters = "departure_fk=318781&departure_date=16%2F04%2F2017&arrival_fk=380553&trip_type=one-way&adults=1&children=0&infants=0&from_filter=Coventry+%28COV%29%2C+United+Kingdom&to_filter=London%2C+United+Kingdom&travel_mode=bus&ab_test_enabled=";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
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();
//print result
System.out.println(response.toString());
}
However, i found my answers from github issue.
Here are required params and there expected json format.
{
"arrivalPosition":{
"positionId":380244
},
"currency":"EUR",
"departurePosition":{
"positionId":380553
},
"domain":"com",
"inboundDate":"2017-04-19T00:00:00.000",
"locale":"en",
"outboundDate":"2017-04-18T00:00:00.000",
"passengers":[
{
"age":18,
"rebates":[]
}
],
"resultFormat":{
"splitRoundTrip":true
},
"searchModes":[
"directbus"
]
}