I want to get the response to a string variable from the data from the cloud.
ClientResource cr = new ClientResource("http://localhost:8888/users");
cr.setRequestEntityBuffering(true);
try {
try {
cr.get(MediaType.APPLICATION_JSON).write(System.out);
} catch (IOException e) {
e.printStackTrace();
}
} catch (ResourceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I have response as JSON in the console and I want to convert it to string , Is the GSON library would be helpful? I haven't used it yet .What modifications should I need to do in my codes? Can anybody help me here.
In fact, Restlet receives the response payload as String and you can directly have access to this, as described below:
ClientResource cr = new ClientResource("http://localhost:8888/users");
cr.setRequestEntityBuffering(true);
Representation representation = cr.get(MediaType.APPLICATION_JSON);
String jsonContentAsString = representation.getText();
Hope it helps you,
Thierry
Below is a working example:
try {
URL url = new URL("http://localhost:8888/users");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
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())));
String output;
System.out.println("Raw 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();
}
}
Related
I have a String which is a SOAP message.
String message = "<?xml version="1.0" encoding="UTF-8"?><SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header>
<xyz:Config xmlns:hal="http://example.com/xyz" applicationId="Client" conversationId="000" host="ENDPOINT">
</xyz:Config>
</SOAP-ENV:Header>
<SOAP-ENV:Body>
<PaymentRQ xmlns="http://www.iata.org/IATA/4/0"
xmlns:common="http://www.iata.org/IATA/common/4/0">
<PaymentDetails>
<PaymentDetail>
<common:PaymentCard CardNumber="1233444444444" CardType="100" ExpireDate="1120" SeriesCode="123">
</PaymentDetail>
</PaymentDetails>
</PaymentRQ>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
";
I need to send this as a SOAP request to a local server running on 8080
So, url would be http://localhost:8080/XYZService/xyz
Then fetch the SOAP response and read its values.
Kindly assist on how I can send the String as a SOAP message to the aforementioned url. Thanks in advance.
You can pass null to SOAPAction if you don't have one.
for serverAddress pass serverIp + ServerPort(ex: 172...*:8088).
public String sendSoapRequest(String serverAdress, String message , String SOAPAction)
{
OutputStream httpOutputStream = null;
byte[] byteArrayStream = message .getBytes();
URL url = null;
try {
url = new URL("http://"+serverAdress);
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpURLConnection httpURLConnection = null;
try {
httpURLConnection = (HttpURLConnection)url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
// Set the appropriate HTTP parameters.
httpURLConnection.setRequestProperty("Content-Length",
String.valueOf(byteArrayStream.length));
httpURLConnection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
httpURLConnection.setRequestProperty("SOAPAction", SOAPAction);
try {
httpURLConnection.setRequestMethod("POST");
} catch (ProtocolException e) {
e.printStackTrace();
}
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
try {
httpOutputStream = httpURLConnection.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
//Write the content of the request to the outputstream of the HTTP Connection.
try {
httpOutputStream.write(byteArrayStream);
httpOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader httpInputBuufferedReader = null;
try {
httpInputBuufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
Log.e(LOG_TAG,"IOException reading HTTP Input message ");
return null;
}
//Write the SOAP message response to a String.
StringBuilder returnOutputString = new StringBuilder();
try {
String line = "";
while ((line = httpInputBuufferedReader.readLine()) != null) {
returnOutputString.append(line);
}
} catch (IOException e) {
e.printStackTrace();
Log.e(LOG_TAG, "IOEception while reading HTTP input buffered reading");
}
return returnOutputString.toString();
}
Ive got
HttpURLConnection urlConnection = null;
String result = "";
try {
String host = "http://www.example.com/json.json";
URL url = new URL(host);
urlConnection = (HttpURLConnection) url.openConnection();
int code = urlConnection.getResponseCode();
if(code==200){
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
if (in != null) {
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject)jsonParser.parse(new InputStreamReader(in, "UTF-8"));
result=(String) jsonObject.get("name");
System.out.print(jsonObject);
}
in.close();
} else { result="9";}
return result;
} catch (MalformedURLException e) {
result="9";
} catch (IOException e) {
result="9";
}
catch (ParseException e) {
e.printStackTrace();
result="9";
}
finally {
urlConnection.disconnect();
}
return result;
When i input valid json data, all is OK, but if i got non json data, i got aplication crash with :
Caused by: java.lang.ClassCastException: java.lang.Long cannot be cast to org.json.simple.JSONObject
I think that
catch (ParseException e) {
e.printStackTrace();
result="9";
}
should handle this, but no.
So what i must do to avoid situation that aplication will crash when i do not get valid json?
The thrown exception is a ClassCastException. Maybe you can catch that exception also by adding another catch?
catch (ClassCastException e) {
e.printStackTrace();
result="9";
}
Try this to make a http request
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
URL myUrl = null;
HttpURLConnection conn = null;
String response = "";
//String data = params[0];
try {
myUrl = new URL("http://www.example.com/json.json");
conn = (HttpURLConnection) myUrl.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
//one long string, first encode is the key to get the data on your web
//page, second encode is the value, keep concatenating key and value.
//theres another ways which easier then this long string in case you are
//posting a lot of info, look it up.
String postData = URLEncoder.encode("key", "UTF-8") + "=" +
URLEncoder.encode("value", "UTF-8");
OutputStream os = conn.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
bufferedWriter.write(postData);
bufferedWriter.flush();
bufferedWriter.close();
InputStream inputStream = conn.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String line = "";
while ((line = bufferedReader.readLine()) != null) {
response += line;
}
bufferedReader.close();
inputStream.close();
conn.disconnect();
os.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
} catch (JSONException e) {
//s may not be json
}
}
}
Before getting String from Json Object, check whether the Json object is not null and has that string. and then try to get it.
if (jsonObject!=null && jsonObject.has("name"))
{
result = jsonObject.get("name");
System.out.print(result);
}
I'm trying to do a "PUT" request with Android Studio.
But, actually, it doesn't work, I received a "404 not found" whereas I got all the needed infos.
String url = "https://[...]";
URL obj = null;
try {
obj = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpURLConnection con = null;
DataOutputStream dataOutputStream = null;
try {
con = (HttpURLConnection) obj.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
// optional default is GET
try {
con.setRequestMethod("PUT");
con.setDoInput(true);
con.setDoOutput(true);
System.out.println("Info User to update : " + params[0]);
con.setRequestProperty("X-Auth-Token", params[0].get("token"));
[...]
con.setRequestProperty("shop_id", params[1].get("id"));
dataOutputStream = new DataOutputStream(con.getOutputStream());
OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
osw.flush();
osw.close();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if (dataOutputStream != null) {
try {
dataOutputStream.flush();
dataOutputStream.close();
} catch (IOException exception) {
exception.printStackTrace();
}
}
}
int responseCode = 0;
try {
responseCode = con.getResponseCode();
} catch (IOException e) {
e.printStackTrace();
}
If I try the request on Symfony (web app), it's worked well, but with the code, not anymore... Do you see any problems with my request ?
Problem solved, I was able to do what I wanted using a PATCH request instead.
I don't know why i get a null value when i call the GetPHPData() function. The "out" variable returns nothing (""). I make a Toast.makeTest and it returns empty string. Please help. This is my code:
public class PHPConnect extends Activity
{
String url = "http://122.2.8.226/MITBookstore/sqlconnect.php";
HttpURLConnection urlConnection = null;
String out = null;
public String GetPHPData()
{
try {
urlConnection = (HttpURLConnection) new URL(url).openConnection();
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(10000);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try
{
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
out = readStream(in);
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
finally
{
urlConnection.disconnect();
return out;
}
}
private String readStream(BufferedReader is)
{
try
{
ByteArrayOutputStream bo = new ByteArrayOutputStream();
int i = is.read();
while(i != -1)
{
bo.write(i);
i = is.read();
}
return bo.toString();
} catch (IOException e)
{
return e.getMessage();
}
}
}
By the way, im running a wamp server and I port forwarded my router, on local host, the url works, but on remote connection, it won't return a string. You can try out the url, the result is: "This is the output:emil"
Can you please try below piece of code which is working for me, also add INTERNET permission in android manifest file. Still if it is not working then may be issue with server end then try to debug it.
URL url;
try {
url = new URL("myurl");
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
System.out.print(current);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I'm trying to POST some data to an https url, in my android application, in order to get a json format response.
I'm facing two problems:
is = conn.getInputStream();
throws
java.io.FileNotFoundException
I don't get if i do something wrong with HttpsURLConnection.
The second problem arose when i debug the code (used eclipse); I set a breakpoint after
conn.setDoOutput(true);
and, when inspecting conn values, I see that the variable doOutput remain set to false and type GET.
My method for https POST is the following, where POSTData is a class extending ArrayList<NameValuePair>
private static String httpsPOST(String urlString, POSTData postData, List<HttpCookie> cookies) {
String result = null;
HttpsURLConnection conn = null;
OutputStream os = null;
InputStream is = null;
try {
URL url = new URL(urlString);
conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setUseCaches (false);
conn.setDoInput(true);
conn.setDoOutput(true);
if(cookies != null)
conn.setRequestProperty("Cookie",
TextUtils.join(";", cookies));
os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(postData.getPostData());
writer.flush();
writer.close();
is = conn.getInputStream();
BufferedReader r = new BufferedReader(
new InputStreamReader(is));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
result = total.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
if (conn != null) {
conn.disconnect();
}
}
return result;
}
A little update: apparently eclipse debug lied to me, running and debugging on netbeans shows a POST connection. Error seems to be related to parameters i'm passing to the url.
FileNotFoundException means that the URL you posted to doesn't exist, or couldn't be mapped to a servlet. It is the result of an HTTP 404 status code.
Don't worry about what you see in the debugger if it doesn't agree with how the program behaves. If doOutput really wasn't enabled, you would get an exception obtaining the output stream.