this block neither gives an error in the log nor does it put any value in the string body
try {
int roll = 00111502713;
//url defined is completely fine//
URL url = new URL("someurl");
URLConnection con = url.openConnection();
InputStream in = con.getInputStream();
encoding = con.getContentEncoding();
encoding = encoding == null ? "UTF-8" : encoding;
try {
body = IOUtils.toString(in, encoding);
Toast.makeText(FirstActivity.this, "Body found", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Log.e("Log_tag", "Hahaha");
}
} catch (Exception ex) {
// System.out.println("This shouldn't have happened");
Log.e("Log_Tag", "Really?");
}
You have to call:
Toast.makeText(FirstActivity.this,"Body found",Toast.LENGTH_SHORT).show();
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();
}
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 have a class audio sender which makes a connection to the nodejs server and uploads an audio file in POST method mode.
public class AudioSender implements Callable<JSONObject> {
String outputFile;
AudioSender(String fileLocation){
outputFile=fileLocation;
}
public JSONObject call(){
URL url = null;
HttpURLConnection urlConnection = null;
InputStream audioInputStream=null;
JSONObject response=null;
byte buffer[]=new byte[16];
try {
url = new URL("http://192.168.0.106:3000/upload");
} catch (MalformedURLException e) {
e.printStackTrace();
} finally {
try {
urlConnection = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
} finally {
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(16);
urlConnection.setRequestProperty("Content-Type","multipart/form-data");
urlConnection.setRequestProperty("Connection", "Keep-Alive");
urlConnection.setRequestProperty("Cache-Control", "no-cache");
urlConnection.setRequestProperty(
"Content-Type", "multipart/form-data;boundary=*****");
try {
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
try {
audioInputStream = new BufferedInputStream(new FileInputStream(outputFile));
Log.d("hello","audioinputstream");
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
while(audioInputStream.read(buffer)!=-1) {
out.write(buffer);
Log.d("buffer",buffer.toString());
}
try {
audioInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
StringBuilder total = new StringBuilder();
while(in.read(buffer)!=-1)
total.append(buffer);
Log.d("response",total.toString());
try {
response = new JSONObject(total.toString());
}catch(JSONException e){
Log.e("Response Parse Error", "Could not parse malformed JSON");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response;
}
This is the upload that executes the AudioSender callable.
public void upload() {
JSONObject response=null;
AudioSender sender=new AudioSender(outputFile);
FutureTask<JSONObject> uploadTask=new FutureTask<JSONObject>(sender);
ExecutorService executorService= Executors.newFixedThreadPool(1);
executorService.execute(uploadTask);
Log.d("s","was here");
while(true){
if(uploadTask.isDone()){
try{
response=uploadTask.get();
}catch(InterruptedException|ExecutionException e){
e.printStackTrace();
Log.e("ee","ee",e.getCause());
}
}
}
}
I pretty much know this isn't node js's fault but here's the server code:
app.post('/upload',function(req,res){
console.log("someone called!");
req.on('data',function(chunk){
console.log('res');
console.log(chunk);
});
req.on('end',function(){
console.log("done!");
res.send({'name':'sg'});
});});
When I call upload(), the server console prints
someone called!
done!
I was debugging and found that indeed I am receiving the responded json object from the server. And I don't know if out.write(buffer) is doing the job, but debugging it shows that the buffer value is changing and is in par with my audio file's size.
Please do not suggest using ION or anything else.
I solved the problems by setting up the URLConnection as follows:
boundary = "===" + System.currentTimeMillis() + "===";
urlConnection.setUseCaches(false);
urlConnection.setDoOutput(true); // indicates POST method
urlConnection.setDoInput(true);
urlConnection.setRequestProperty("Content-Type","multipart/form-data; boundary=" + boundary);
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();
}
}
I am trying to retrieve a url with an umlaut in the filename, something like "http://somesimpledomain.com/some/path/überfile.txt", but it gives me a java.io.FileNotFoundException. I suspect that the filename on the remote server is encoded in latin1, though my url is in utf8. But my tries to change the encoding of the url weren't successful and I don't know how to debug it further. Please help!
Code is as follows:
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) new URL(uri).openConnection();
conn.setRequestMethod("GET");
} catch (MalformedURLException ex) {}
} catch (IOException ex){}
// Filter headers
int i=1;
String hKey;
while ((hKey = conn.getHeaderFieldKey(i)) != null) {
conn.getHeaderField(i);
i++;
}
// Open the file and output streams
InputStream in = null;
OutputStream out = null;
try {
in = conn.getInputStream();
} catch (IOException ex) {
ex.printStackTrace();
}
try {
out = response.getOutputStream();
} catch (IOException ex) {
}
Regards,
Hendrik
URL needs to be properly encoded. You have to know what charset/encoding your server is expecting. You can try this first,
String uri = "http://somesimpledomain.com/some/path/" +
URLEncoder.encode(filename, "ISO-8859-1");
If that doesn't work, replace "ISO-8859-1" with "UTF-8" and try again.
If that doesn't work either, file doesn't exist :)
Have you tried urlencoding it? E.g.
%FCberfile