I'm getting HTML response instead of JSON response. I'm using following code and I'm receiving HTML response as bf.readLine(). Is there any issue in following code or is this API issue?
String uri = "http://192.168.77.6/Ivr_ABN_API/?id=" + mobile;
URL url;
Gson json = null;
try {
url = new URL(uri);
json = new Gson();
HttpURLConnection connection;
access_token = db.getAccessTokenFromDB();
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
System.out.println("URL:" + uri);
connection.setRequestProperty("Content-Type", "application/json");
int status = connection.getResponseCode();
resCode = Integer.toString(status);
System.out.println("status is " + status);
InputStream in = connection.getInputStream();
System.out.println("inputStreamer " + in);
BufferedReader bf = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
System.out.println("bf.readLine() - " + bf.readLine());
while ((output = bf.readLine()) != null) {
JSONObject obj = new JSONObject(output);
System.out.println("output is " + output);
resCode = obj.getString("resCode");
resDesc = obj.getString("COUNT");
}
Perhaps try sending the header Accept: application/json
If that doesn't work, then review the documentation for the API and see if there's something else you should be sending to return json.
For java
Set The Request Property as the following:
con.setRequestProperty("Accept","application/json")
It will solve the issue you are facing.
Related
I'am new in JWT so i need to get a token with JAVA code from a webService (GET Method).
In postMan i was able to get the token (below the screenshot).
I used this java code but this return often Response Code : 403
String url = "https://WEBSERVICE_LINK";
try {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
this.log.info("Sending 'GET' request to URL : " + url);
con.setRequestProperty("Authorization", Base64.getEncoder().encodeToString((username + ":" + pwd).getBytes()));
con.setRequestProperty("Accept", "application/json");
int responseCode = con.getResponseCode();
this.log.info("Response Code : " + responseCode);
StringBuilder response;
try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
String inputLine;
response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
}
String reponseString = response.toString();
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(reponseString);
// Isoler et transmettre le Token
this.token = jsonNode.get("token") != null ? jsonNode.get("token").asText() : null;
this.log.info("Token : " + this.token);
Thank you
You seem to have forgotten the Basic prefix in the Authorization header value:
con.setRequestProperty(
"Authorization",
"Basic " + Base64.getEncoder().encodeToString((username + ":" + pwd).getBytes())
);
I am trying to read JSON data with Java, I was successfully to read the first array, below is my JSON report from url.
{
"success":1,
"object":"sale",
"id":"sl987575",
"created":"2019-08-03 21:40:35",
"product_id":"prd00123",
"product_name":"AirBuss",
"amount":"100.00",
"currency":"USD",
"status":"Completed",
"meta":[],
"customer":{
"object":"customer",
"id":"001234",
"email":"someone#email.com",
"name":"Full Name",
"country":null,
"firstname":"Full",
"lastname":"Name"}}
I can read "product_name" and "status" but cannot read the "email" data.
public static void call_me() throws Exception {
String url = "Link WEbsite/api/?apiKey=23459876";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", "Mozilla/5.0");
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 in String
System.out.println(response.toString());
//Read JSON response and print
JSONObject myResponse = new JSONObject(response.toString());
System.out.println("result after Reading JSON Response");
System.out.println("Product Name : "+myResponse.getString("product_id"));
System.out.println("status : "+myResponse.getString("status"));
System.out.println("Email : "+myResponse.getString("email"));
}
Try this:
System.out.println("Email : " + myResponse.getJSONObject("customer").getString("email"));
Because 'email', 'country' etc. fields in a nested object named customer.
I just found solution for my own question..
JSONObject customer_data = myResponse.getJSONObject("customer");
System.out.println("Email : "+customer_data.getString("email"));
I am trying to call a web service using a java code which is throwing java.io.EOFException: Response had end of stream after 0 bytes for the large chunk of data.
The same web service call works in Postman REST Client, but Java code throws an error and it is not able to fetch web service response.
Can someone please help me with this?
Below is the code snippet for reference:
String output;
URL url = new URL(wsUrl); //wsUrl is a web service URL
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
String authorization = "**************" + ":" + "*********";
String basicAuth = "Basic " + java.util
.Base64
.getEncoder()
.encodeToString(authorization.getBytes());
conn.setRequestProperty("Authorization", basicAuth);
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())));
System.out.println("Output from Server .... \n");
String jsonstring = new String();
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
The code below shows a method, downloadUrl(), that takes a String, "myurl," its parameter. There are only two possible urls that I ever send to it, and the behavior of the method is different for each.
when myurl = URL1, it uses a GET request and everything works fine.
when myurl = URL2, however, it uses a POST request, and the response from the php page indicates that the post parameters sent with the request were empty. You can see the line where I set the POST params, so I don't understand why it's sending no params?!
Thanks for any help!
-Adam.
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
String response = "";
try {
URL urlObject = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) urlObject.openConnection();
// find out if there's a way to incorporate these timeouts into the progress bar
// and what they mean for shitty network situations
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setDoInput(true);
// INSERTED QUICK CHECK TO SEE WHICH URL WE ARE LOADING FROM
// it's important because one is GET, and one is POST
if (myurl.equals(url2)){
Log.i(TAG, "dlurl() in async recognizes we are doing pre-call");
conn.setRequestMethod("POST");
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
String postParams = "?phone=" + phone;
writer.write(postParams);
Log.i(TAG, "we're adding " + postParams + "to " + urlObject);
writer.flush();
writer.close();
os.close();
}
else {
conn.setRequestMethod("GET");
conn.connect();
}
// Starts the query
int responseCode = conn.getResponseCode();
Log.i(TAG, "from " + myurl + ", The response code from SERVER is: " + responseCode);
is = conn.getInputStream();
// Convert the InputStream into a string
// i guess we look up how to do this
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
response += line;
}
} else {
response = "from downloadUrl, php page response was not OK: " + responseCode;
}
// it's good to close these things?
is.close();
conn.disconnect();
Log.i(TAG, "response is " + response);
return response;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
try with following code block to send parameters of the POST request.
Map<String,String> params = new LinkedHashMap<>();
params.put("phone", "phone");
StringBuilder postPraamString = new StringBuilder();
for (Map.Entry<String,Object> param : params.entrySet()) {
if (postPraamString.length() != 0) postPraamString.append('&');
postPraamString.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postPraamString.append('=');
postPraamString.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
writer.write(postDataBytes);
So I figured out the root of the problem...
In the line:
String postParams = "?phone=" + phone;
The problem was that leading question mark. The question mark should only be used in GET requests.
I'm trying to send email using the SES HTTPS Query API. I have a java method that sends a GET request to an Amazon SES endpoint, I'm trying to send an email with SES and capture the result.
Code:
public static String SendElasticEmail(String timeConv,String action,String source, String destinationAddr, String subject, String body) {
try {
System.out.println("date : "+timeConv);
System.out.println("In Sending Mail Method......!!!!!");
//Construct the data
String data = "Action=" + URLEncoder.encode(action, "UTF-8");
data += "&Source=" + URLEncoder.encode(source, "UTF-8");
data += "&Destination.ToAddresses.member.1=" + URLEncoder.encode(destinationAddr, "UTF-8");
data += "&Message.Subject.Data=" + URLEncoder.encode(subject, "UTF-8");
data += "&Message.Body.Text.Data=" + URLEncoder.encode(body, "UTF-8");
//Send data
System.out.println("https://email.us-east-1.amazonaws.com?"+data);
URL url = new URL("https://email.us-east-1.amazonaws.com?"+data);
//URLConnection conn = url.openConnection();
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("x-amz-date" , timeConv);
con.setRequestProperty("Content-Length", ""+data.toString().length());
con.setRequestProperty("X-Amzn-Authorization" , authHeader);
int responseCode = ((HttpsURLConnection) con).getResponseCode();
String responseMessage = ((HttpsURLConnection) con).getResponseMessage();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
//System.out.println("Response Message : " + responseMessage);
InputStream stream = con.getInputStream();
InputStreamReader isReader = new InputStreamReader(stream );
System.out.println("hgfhfhfhgfgfghfgh");
BufferedReader br = new BufferedReader(isReader);
String result = "";
String line;
while ((line = br.readLine()) != null) {
result+= line;
}
System.out.println(result);
br.close();
con.disconnect();
}
catch(Exception e) {
e.printStackTrace();
}
return subject;
}
I have calculated the signature correctly, because on hitting from postman client getting 200 response.
URL url = new URL("https://email.us-east-1.amazonaws.com?"+data);
You missed a '/' before the question mark. It should be
URL url = new URL("https://email.us-east-1.amazonaws.com/?"+data);