Get Json / Resonse body from Curl Post Request in Java - java

This is the method I have written which sends a POST request to send an Email.
I am able to send the email and get the Response Code 200 Ok.
But I don't know how to get the JSON Response and convert it into an Object.
Can someone please tell me how to do this?
public void sendEmail() {
try {
URL url = new URL("https://mandrillapp.com/api/1.0/messages/send");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestProperty("Content-Type", "application/json");
String data =
"{\"key\": \"" + mailchimpApiKey + "\", " +
"\"message\": {" +
"\"from_email\": \"from#gmail.com\", " +
"\"subject\": \"Hello World\", " +
"\"text\": \"Welcome to Mailchimp Transactional!\", " +
"\"to\": [{ \"email\": \"to#gmail.com\", \"type\": \"to\" }]}}";
byte[] out = data.getBytes(StandardCharsets.UTF_8);
OutputStream stream = httpURLConnection.getOutputStream();
stream.write(out);
System.out.println(httpURLConnection.getResponseCode() + " " + httpURLConnection.getResponseMessage());
httpURLConnection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}

A basic search reveals: https://www.baeldung.com/httpurlconnection-post#8-read-the-response-from-input-stream
try(BufferedReader br = new BufferedReader(
new InputStreamReader(con.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println(response.toString());
}
If the response is in JSON format, use any third-party JSON parsers such as Jackson library, Gson, or org.json to parse the response.

In addition to the answer by #mdre
I use the org.json library to convert responses into JSON Objects. The following method does exactly this:
import org.json.JSONException;
import org.json.JSONObject;
public static JSONObject convertResponseToJSONObject(String responseString) {
try {
JSONObject jsonObj = new JSONObject(responseString);
return jsonObj;
} catch (JSONException e) {
System.err.println(
"It is not possible to create a JSONObject from the input string, returning null. Exception:");
e.printStackTrace();
}
return null;
}
Note that the response only represents a JSON object if it starts with a {. If it starts with a [ the response represents a JSON array.

You can get errorStream or inputStream based on the response code you receive and get the response from it. Below example creates a BufferedReader from the stream
BufferedReader br = null;
if (100 <= httpURLConnection.getResponseCode() && httpURLConnection.getResponseCode() <= 399) {
br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
} else {
br = new BufferedReader(new InputStreamReader(httpURLConnection.getErrorStream()));
}
You can then read from the br and store data based on your requirement. Below will store data into StringBuilder
StringBuilder data = new StringBuilder();
String dataLine = null;
while ((dataLine = br.readLine()) != null) {
data.append(dataLine.trim());
}
System.out.println(data.toString());
Instead of printing as String you can also convert it into JSON by using JSON libraries. You may follow this guide

Related

Reading rest service of content type application/vnd.oracle.adf.resourceitem+json

I have a webservice whose content type is application/vnd.oracle.adf.resourceitem+json.
The HttpEntity of the reponse obtained by hitting this service is looks like this
ResponseEntityProxy{[Content-Type: application/vnd.oracle.adf.resourceitem+json,Content-Length: 3,Chunked: false]}
When I try to convert this HttpEntity into String it gives me a blank String {}.
Below are the ways I tried to convert the HttpEntity to String
1.
String strResponse = EntityUtils.toString(response.getEntity());
2.
String strResponse = "";
String inputLine;
BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
try {
while ((inputLine = br.readLine()) != null) {
System.out.println(inputLine);
strResponse += inputLine;
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
3.
response.getEntity().writeTo(new FileOutputStream(new File("C:\\Users\\harshita.sethi\\Documents\\Chabot\\post.txt")));
All returns String -> {}.
Can anyone tell me what am I doing wrong?
Is this because of the content type?
The above code is still giving the same response with empty JSON object. So I modified and wrote the below code. This one seems to run perfectly fine.
URL url = new URL(urlString);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.addRequestProperty("Authorization", getAuthToken());
con.addRequestProperty("Content-Type", "application/vnd.oracle.adf.resourceitem+json;charset=utf-8");
String input = String.format("{\"%s\":\"%s\",\"%s\":\"%s\"}", field, value, field2, value2);
System.out.println(input);
OutputStream outputStream = con.getOutputStream();
outputStream.write(input.getBytes());
outputStream.flush();
con.connect();
System.out.println(con.getResponseCode());
// Uncompressing gzip content encoding
GZIPInputStream gzip = new GZIPInputStream(con.getInputStream());
StringBuffer szBuffer = new StringBuffer();
byte tByte[] = new byte[1024];
while (true) {
int iLength = gzip.read(tByte, 0, 1024);
if (iLength < 0) {
break;
}
szBuffer.append(new String(tByte, 0, iLength));
}
con.disconnect();
returnString = szBuffer.toString();
Authentication method
private String getAuthToken() {
String name = user;
String pwd = this.password;
String authString = name + ":" + pwd;
byte[] authEncBytes = Base64.getEncoder().encode(authString.getBytes());
System.out.println(new String(authEncBytes));
return "Basic " + new String(authEncBytes);
}
In case anybody faces the same issue. Let me share the challenged I faced and how I rectified those.
The above code works for all content-types/methods. Can be used for any type (GET, POST, PUT,DELETE).
For my requirement I had a POST webservice with
Content-Encoding →gzip
Content-Type →application/vnd.oracle.adf.resourceitem+json
Challenges : I was able to get the correct response code but I was getting junk characters as my response string.
Solution : This was because the output was compressed in gzip format which needed to be uncompressed.
The code of uncompressing the gzip content encoding is also mentioned above.
Hope it helps future users.

POST params empty, what am I doing wrong? HttpURLConnection / Android / Java

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.

Request to server API using Java and JSON

I have documentation of server API with several methods. The problem is that I have never used API to work with server. What I can do to do it more easy?
Part of API documentation:
Method "Login":
POST http://api.example.com/login-ajax
Parameters:
email
password
Response:
{
"success":true,
"currentUser":222,
"userData":{
"displayName":"User",
"displayAvatarId":"asjhdsasduh",
"email":"qwerty#gmail.com",
"isEmailConfirmed":"0",
"sex":"m"
}
}
The response is JSON object, but I don't know how to send request to get this response.
Help me please.
UPGRADE
I tried to use Jsoup:
Connection.Response res = Jsoup.connect("http://api.example.com/login-ajax")
.data("email", "mail#gmail.com", "password", "pass")
.method(Connection.Method.POST)
.header("Accept", "application/json")
.header("X-Requested-With", "XMLHttpRequest")
.header("X-App-Api", "1.0")
.header("X-App", "iOS")
.ignoreContentType(true)
.execute();
Document document = Jsoup.parse(res.parse().outerHtml());
System.out.println(document.text());
The response is:
{"success":false,"exception":"Exception_User","message":"\u041c\u044b \u043d\u0435 \u043d\u0430\u0448\u043b\u0438 \u0432 \u0431\u0430\u0437\u0435 \u0442\u0430\u043a\u043e\u0435 \u0441\u043e\u0447\u0435\u0442\u0430\u043d\u0438\u0435 \u044d\u043b. \u043f\u043e\u0447\u0442\u044b \u0438 \u043f\u0430\u0440\u043e\u043b\u044f. \u041f\u043e\u0436\u0430\u043b\u0443\u0439\u0441\u0442\u0430, \u043f\u043e\u043f\u0440\u043e\u0431\u0443\u0439\u0442\u0435 \u0435\u0449\u0435 \u0440\u0430\u0437."}
UPGRADE 2
I also tried to use this one:
System.out.println(getJSON("http://api.example.com/login-ajax"));
public static String getJSON(String url) {
try {
URL u = new URL(url);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("POST");
c.setRequestProperty("email", "mail#gmail.com");
c.setRequestProperty("password", "pass");
c.setRequestProperty("Accept", "application/json");
c.setRequestProperty("X-Requested-With", "XMLHttpRequest");
c.setRequestProperty("X-App-Api", "1.0");
c.setRequestProperty("X-App", "iOS");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setConnectTimeout(1000);
c.setReadTimeout(1000);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
System.out.println("200");
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
return sb.toString();
case 201:
System.out.println("201");
br = new BufferedReader(new InputStreamReader(c.getInputStream()));
sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
return sb.toString();
}
} catch (MalformedURLException ex) {
System.out.println("MalformedURLException");
} catch (IOException ex) {
System.out.println("IOException");
}
return null;
}
And the response is:
{"success":false,"exception":"Exception_Validation","message":"\u041d\u0435\u043f\u0440\u0430\u0432\u0438\u043b\u044c\u043d\u044b\u0439 e-mail","errors":{"email":["\u041f\u043e\u0436\u0430\u043b\u0443\u0439\u0441\u0442\u0430, \u0432\u0432\u0435\u0434\u0438\u0442\u0435 e-mail."],"password":["\u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u043f\u0430\u0440\u043e\u043b\u044c"]}}
As I haven't used Jsoup so far I can't give detailed information on how to use it, but I had to work with Restlet and therefore created my own JSON messages (either via org.json.JSONObject or via plain String). A post-example using Restlet would look something like this:
try
{
// create a Restlet client
ClientResource cr = new ClienResource("http://api.example.com/login-ajax");
// create the JSON message
JSONObject message = new JSONObject();
message.put("email", "mail#gmail.com");
message.put("password", "pass");
// use HTTP POST method to send the JSON message
cr.post(message, MediaType.APPLICATION_JSON);
// receive the answer - error checks omitted!
Response response = cr.getResponse();
JsonRepresentation jsonRep = new JsonRepresentation(response.getEntity());
// process the JSON response
JSONObject json = jsonRep.getJsonObject();
System.out.println("success: "+json.get("success"));
System.out.println("current user: "+json.get("currentUser"));
// extract the user data
JSONObject userData = (JSONObject)json.get("userData");
System.out.println("display name: "+userData.get("displayName"));
System.out.println("display avatar Id: "+userData.get("displayAvatarId"));
System.out.println("email: "+userData.get("email"));
System.out.println("is email confirmed: "+userData.get("isEmailConfirmed"));
System.out.println("sex: "+userData.get("sex"));
}
catch (ResourceException | JSONException ex)
{
ex.printStackTrace();
}
HTH
Consider to use an Apache HTTP Client to create a connection to your HTTP server.
Its a general-purpose library for working with HTTP requests. There are plenty resources that illustrate the usage of HTTP client, Here is an example
I admit, I've never used JSoup so I can't really comment on your example.
Hope this helps,
Mark

Place detail request failing - reference too long

I have a small java app that, given a list of references for google places, must get back the Id's for each of said google places (long story short, we were storing references for places instead of their Id's, and only now realized that references are not unique per place).
My app works perfectly for about 95% of the places in the list, but fails with a "NOT_FOUND" status code for some records. Some investigation reveals that the place reference for these particular places is (when combined with the https://maps.googleapis.com/maps/api/place/details/json?sensor=false&key=myApiKey prefix) about 2 characters too long for a URL. The last couple of characters are getting truncated.
My initial thought was that I would just make a POST request to the google places API, but I'm getting back "REQUEST_DENIED" status code from the google servers when sending the same into as a POST request.
Is there anyway around this, or is this just an emergent bug with the google places API (now that the number of places has pushed the reference too long?).
I should also note that the places that fail are all recently added by our application.
This is what my current (working for 95%) code looks like:
public static JSONObject getPlaceInfo(String reference) throws Exception
{
URL places = new URL("https://maps.googleapis.com/maps/api/place/details/json?sensor=false&key="+apiKey+"&reference="+reference);
URLConnection con = places.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuffer input = new StringBuffer();
String inputLine;
while ((inputLine = in.readLine()) != null)
input.append(inputLine);
in.close();
JSONObject response = (JSONObject) JSONSerializer.toJSON(input.toString());
return response;
}
and this is what my "ACCESS_DENIED" post code looks like:
public static JSONObject getPlaceInfo(String reference) throws Exception
{
String data = URLEncoder.encode("sensor", "UTF-8") + "=" + URLEncoder.encode("true", "UTF-8");
data += "&" + URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode(apiKey, "UTF-8");
data += "&" + URLEncoder.encode("reference", "UTF-8") + "=" + URLEncoder.encode(reference, "UTF-8");
URL places = new URL("https://maps.googleapis.com/maps/api/place/details/json");
URLConnection con = places.openConnection();
con.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuffer input = new StringBuffer();
String inputLine;
while ((inputLine = in.readLine()) != null)
input.append(inputLine);
in.close();
JSONObject response = (JSONObject) JSONSerializer.toJSON(input.toString());
return response;
}
An example of the reference that fails is:
CnRtAAAAxm0DftH1c5c6-krpWWZTT51uf0rDqCK4jikWV6eGfXlmKxrlsdrhFBOCgWOqChc1Au37inhf8HzjEbRdpMGghYy3dxGt17FEb8ys2CZCLHyC--7Vf1jn-Yn1kfZfzxznTJAbIEg6422q1kRbh0nl1hIQ71tmdOVvhdTfY_LOdbEoahoUnP0SAoOFNkk_KBIvTW30btEwkZs
Thanks in advance!
You're sending your request parameters in the body, which isn't supported by the API. There's a good answer about GET and request params at:
HTTP GET with request body
The following code should work for Place detail requests:
private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place";
private static final String TYPE_DETAILS = "/details";
private static final String OUT_JSON = "/json";
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
try {
StringBuilder sb = new StringBuilder(PLACES_API_BASE);
sb.append(TYPE_DETAILS);
sb.append(OUT_JSON);
sb.append("?sensor=false");
sb.append("&key=" + API_KEY);
sb.append("&reference=" + URLEncoder.encode(reference, "utf8"));
URL url = new URL(sb.toString());
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Load the results into a StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
} catch (MalformedURLException e) {
return null;
} catch (IOException e) {
return null;
} finally {
if (conn != null) {
conn.disconnect();
}
}
try {
// Create a JSON object hierarchy from the results
JSONObject jsonObj = new JSONObject(jsonResults.toString()).getJSONObject("result");
jsonObj.getString("name");
} catch (JSONException e) {
Log.e(LOG_TAG, "Error processing JSON results", e);
}

Send information from PHP to Java

I want to send some information from PHP to Java. Why? Because I have a database on my server, and I get information from my database using PHP scripts.
Now I want to send that information to my client in Java. How can I do that?
I send information from Java to PHP by POST, and it works well, but I don't know how can I do the reverse.
Can you help me?
I saw this code, from a GET connection in Java... is it correct?
public String HttpClientTutorial(){
String url = "http://testes.neoscopio.com/myrepo/send.php";
InputStream content = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(url));
content = response.getEntity().getContent();
} catch (Exception e) {
Log.e("[GET REQUEST]", "Network exception", e);
}
String response = content.toString();
return response;
}
P.S: I'm an android developer, not a Java developer...
From exampledepot: Sending POST request (Modified to get the output of your send.php.)
try {
// Construct data
String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
// Send data
URL url = new URL("http://testes.neoscopio.com/myrepo/send.php");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
// Process line...
}
wr.close();
rd.close();
} catch (Exception e) {
}
P.S. This should work fine on Android. :)
(I usually import static java.net.URLEncoder.encode but that's a matter of taste.)

Categories

Resources