I am trying to parse a response from an InputStream from a HttpURLConnection using the following code.I get an error when trying to get the InputStream.I am just looking to get a response to check if the web-servcice call worked OK.
static final String SOAP_ACTION="http://888topup.com/ImageProcess.svc/UploadImage";
java.net.URL url=null;
try {
url = new java.net.URL(SOAP_ACTION);
} catch (MalformedURLException e) {
Log.e(TAG, "Bad URL",e);
}
JSONObject obj=new JSONObject();
try {
obj.put("Vaue", value);
} catch (JSONException e) {
Log.e(TAG, "Create JSONObjerct throws an error");
}
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection)url.openConnection();
} catch (IOException e1) {
Log.e(TAG,"Error opening connection",e1);
}
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
try {
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Accept", "*/*");
urlConnection.addRequestProperty("Accept-Encoding", "gzip deflate sdch");
urlConnection.setRequestProperty("Content-Type","application/json");
} catch (ProtocolException e) {
Log.e(TAG,"Error setting header",e);
}
try {
OutputStream os=urlConnection.getOutputStream();
BufferedOutputStream bos=new BufferedOutputStream(os);
byte[] data=obj.toString().getBytes();
bos.write(data);
InputStream is=urlConnection.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String response;
response=br.readLine();
Log.d(TAG, "Response: "+response);
bos.close();
br.close();
is.close();
urlConnection.disconnect();
} catch (IOException e) {
Log.e(TAG,"Error peforming read-write operations",e);
}
Here is the Logcat entry for what happened when I tried to run this code:
MainActivity(9628): Error peforming read-write operations
MainActivity(9628): java.io.FileNotFoundException: http://888topup.com/ImageProcess.svc/UploadImage
MainActivity(9628): at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:186)
MainActivity(8989): at com.example.imageuploadtest.MainActivity.sendStringToServiceUsingRest(MainActivity.java:184)
MainActivity(8989): at com.example.imageuploadtest.MainActivity.access$0(MainActivity.java:149)
MainActivity(8989): at com.example.imageuploadtest.MainActivity$1$1.run(MainActivity.java:66)
EDIT:
The operation as specified in WSDL:
<wsdl:operation name="UploadImage">
<wsdl:input wsaw:Action="http://tempuri.org/IImageProcess/UploadImage" message="tns:IImageProcess_UploadImage_InputMessage"/>
<wsdl:output wsaw:Action="http://tempuri.org/IImageProcess/UploadImageResponse" message="tns:IImageProcess_UploadImage_OutputMessage"/>
</wsdl:operation>
Adding urlConnection.connect() before writing data to the OutputStream does not work either.
EDIT:Using the URL(SOAP_ACTION) and passing jsondata works from Sencha-Touch for someone else who tested it.
Tried passing JSONObject as String instead of byte data.Did not work either?
There were a few mistakes with what I was doing,firstly I was passing the wrong parameter Vaue instead of Value to the service.
JSONObject obj=new JSONObject();
try {
String value_key="Value";
obj.put(value_key, value);
Log.d(TAG,obj.toString());
} catch (JSONException e) {
Log.e(TAG, "Create JSONObjerct throws an error");
}
Secondly,I was trying to parse a response when no response was being sent.So, I replace the code to get the InputStream with the following code:
int response=urlConnection.getResponseCode();
The entire code is here:
java.net.URL url=null;
try {
url = new java.net.URL(SOAP_ACTION);
} catch (MalformedURLException e) {
Log.e(TAG, "Bad URL",e);
}
JSONObject obj=new JSONObject();
try {
String value_key="Value";
obj.put(value_key, value);
Log.d(TAG,obj.toString());
} catch (JSONException e) {
Log.e(TAG, "Create JSONObjerct throws an error");
}
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection)url.openConnection();
} catch (IOException e1) {
Log.e(TAG,"Error opening connection",e1);
}
urlConnection.setDoOutput(true);
try {
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Accept", "*/*");
//urlConnection.addRequestProperty("Accept-Encoding", "gzip deflate sdch");
urlConnection.setRequestProperty("Content-Type","application/json");
} catch (ProtocolException e) {
Log.e(TAG,"Error setting header",e);
}
try {
urlConnection.connect();
DataOutputStream dos=new DataOutputStream(urlConnection.getOutputStream());
dos.write(obj.toString().getBytes());
int response=urlConnection.getResponseCode();
Log.d(TAG, "Response code: "+response);
urlConnection.disconnect();
} catch (IOException e) {
Log.e(TAG,"Error peforming read-write operations",e);
}
And finally I used this to send the data to the web-service as binary data:
DataOutputStream dos=new DataOutputStream(urlConnection.getOutputStream());
dos.write(obj.toString().getBytes());
Related
I am trying to upload a zip file from files from the android application to the server. I am initiating the HttpEntity object and uploading it in bytes using OutputStream and utf-8 char-set.
HttpEntity entity = MultipartEntityBuilder.create()
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.addPart("Solution", fileBody).build();
URL url = null;
try {
url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
try {
connection.setRequestProperty("Content-Type", "application/zip");
connection.setRequestProperty("Accept", "application/zip;");
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
try (OutputStream os = connection.getOutputStream()) {
byte[] input = entity.toString().getBytes("utf-8");
os.write(input, 0, input.length);
}
return connection.getInputStream();
} catch (Exception e) {
Log.v("Exception", e.getMessage());
} finally {
connection.disconnect();
}
} catch (Exception e) {
Log.v("Exception", e.getMessage());
}
On the server, I am receiving empty "Files" object under HttpContext.Current.Request.
[HttpPost]
[Route("UploadProblemSolution")]
public HttpResponseMessage UploadProblemSolution()
{
try
{
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
//save zip files
}
}
catch (Exception ex)
{
}
}
I want to close the get request connection but,it didn't closed.
Its my code block
Edit code block but doesn't work again..
try {
HttpClient client = new DefaultHttpClient();
URI website = website = new URI("http://"+IPAdres+"/?Arduino="+Komut);
HttpGet request = new HttpGet();
request.setURI(website);
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
request.abort();
client.getConnectionManager().shutdown();
client.getConnectionManager().closeExpiredConnections();
} catch (URISyntaxException e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
} catch (ClientProtocolException e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
I want to close connection after request
Android ways are little different from java ways. Can yo try this approach?
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
} finally {
urlConnection.disconnect();
}
To read more on this try this link
I have problem with connecting to my server. Following code returns -1 as response code and null as response message.
protected Boolean doInBackground(MyTaskParams... params) {
URL url = null;
String load = params[0].jobj.toString();
try {
url = new URL(params[0].serverUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(3000);
urlConnection.setReadTimeout(3000);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
urlConnection.setChunkedStreamingMode(0);
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
OutputStreamWriter osw = new OutputStreamWriter(urlConnection.getOutputStream());
osw.write(load);
osw.flush();
osw.close();
if(urlConnection.getResponseCode()==200 && urlConnection.getResponseMessage().contains("true") ) return true;
else return false;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
While debbuging url and body content (which is load in code) are correct. When I try to connect with the server using those params with Fiddler it works perfectly and I get 200 status code. Do you have any ideas what is wrong?
Im passing jData object as the jobj:
JSONObject User=new JSONObject();
JSONObject Mobile=new JSONObject();
JSONObject jData=new JSONObject();
try {
User.put ("UserLogin", "test");
User.put ("UserPassword", "test");
Mobile.put ("MobileIDD", IDD);
Mobile.put("MobileToken", token);
jData.put("Mobile", Mobile);
jData.put("User", User);
} catch (JSONException e) {
e.printStackTrace();
}
#EDIT
Solution with System.setProperty("http.keepAlive", "false") didnt help.
I solved the problem. It was in this line:
if(urlConnection.getResponseCode()==200 && urlConnection.getResponseMessage().contains("true") ) return true;
When I changed it to:
int code = urlConnection.getResponseCode();
if (code==200.....)
It started working.
I have the following code in my program, used for inserting record -
private Void downloadUrl() throws IOException {
String postParameters;
HttpURLConnection urlConnection = null;
postParameters = "name="+ URLEncoder.encode(user.name,"UTF-8")
+"&age="+URLEncoder.encode(user.age+"","UTF-8")
+"&username="+URLEncoder.encode(user.username,"UTF-8")
+"&password="+URLEncoder.encode(user.password,"UTF-8");
if (postParameters != null) {
Log.i("Post", "POST parameters: " + postParameters);
try {
URL urlToRequest = new URL(SERVER_ADDRESS);
urlConnection = (HttpURLConnection) urlToRequest.openConnection();
urlConnection.setReadTimeout(30000 /* milliseconds */);
urlConnection.setConnectTimeout(30000 /* milliseconds */);
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
urlConnection.setFixedLengthStreamingMode(
postParameters.getBytes().length);
PrintWriter out = new PrintWriter(urlConnection.getOutputStream());
out.print(postParameters.getBytes());
out.close();
// handle issues
int statusCode = urlConnection.getResponseCode();
Log.e("Response", "The response is: " + statusCode);
} catch (MalformedURLException e) {
// handle invalid URL
Log.e("Response", "invalid URL");
} catch (SocketTimeoutException e) {
// hadle timeout
Log.e("Response", "handle timeout");
} catch (IOException e) {
// handle I/0
Log.e("Response", "handle IO problem");
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
return null;
}
The code is showing no errors and the logged entries are
09-27 12:24:17.944 5006-5039/? E/Response﹕ The response is: 200
09-27 12:24:33.729 5006-5118/? I/Post﹕ POST parameters: name=vibha&age=25&username=vib&password=1234
But when I check the database, the new record is not created.
But if I use PHP code in a file and post the same parameters,the records are getting inserted.
My requirement for help and guidance is how to pass the post parameter in the HttpURLConnection class
I get an EOFException from getInputStream in the following Android Code.
private void downloadUrl() {
HttpsURLConnection conn = null;
DataOutputStream printout = null;
try {
try {
conn = (HttpsURLConnection) new URL("some url").openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
}
catch (ProtocolException e){
}
JSONObject jsonReq = new JSONObject();
jsonReq.put("userID", "id");
jsonReq.put("password", "1234");
OutputStream output = conn.getOutputStream();
try {
OutputStreamWriter wr = new OutputStreamWriter(output);
wr.write(URLEncoder.encode(jsonReq.toString(),"utf-8"));
wr.flush();
wr.close();
}
catch (IOException e) {
}
InputStream in = conn.getInputStream(); //I get EOFException here
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(in));
String responseSingle = null;
while ((responseSingle = rd.readLine()) != null) {
response = response + responseSingle;
}
rd.close();
}
catch (IOException e) {
}
finally {
if (in != null)
in.close();
}
}
catch (IOException e){
}
catch (JSONException e) {
}
finally{
if(conn!=null)
conn.disconnect();
}
}
What is causing this Exception?
public class EOFException extends IOException:
Signals that an end of file or end of stream has been reached unexpectedly during input.
http://docs.oracle.com/javase/7/docs/api/java/io/EOFException.html
You are calling conn.getOutputStream(); and then calling conn.getInputStream(); without resetting. You are already at the end of the file.