JsonWriter POST not working in Android to WCF web service - android

I would like to know anyone has a sample code on how to use JsonWriter to post JSON data to WCF web service from Android?
I tested my WCF with Fiddler 4 (Composer with POST json data) and it gave me the correct return.
However, when I tested with my Android application which use JsonWriter, I didn't see any action on Fiddler (I set up Fiddler to check on my Android Emulator network traffic, by the way, I am testing on Android Emulator.).
With the same Android application, I can call GET with JsonReader to my WCF and get the correct reply.
Its just calling POST with JsonWriter got no response code or no action in Fiddler.
For JsonWriter (and Reader), I refer to Android developer >> JsonWriter
Here are my test results (Get and Post) with Emulator GET and POST.
Here are my test results with Fiddler direct POST.
First it gave me Result 307 then follow by 200.
And here is how I use JsonWriter to post (this block was from AsyncTask).
try
{
Log.d("TEST_JSON", "URL: " + params[0]);
URL url = new URL(params[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept","application/json");
conn.setRequestProperty("Content-Type","application/json");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
// conn.connect();
OutputStream out = conn.getOutputStream();
JsonWriter writer = new JsonWriter(new OutputStreamWriter(out, "UTF-8"));
try
{
writer.setIndent(" ");
if(params[1].trim() == "ARRAY")
{
// Write array to WCF.
}
else if(params[1].trim() == "OBJ")
{
// Write object to WCF. <<== I am testing with one object.
writer.beginObject();
writer.name("ShipNo").value("SI10101");
writer.name("DoNo").value("DO230401");
writer.name("PartNo").value("102931-1201");
writer.name("Qty").value(1);
writer.name("ShipIn").value(1);
writer.endObject();
}
}
finally
{
writer.close();
out.close();
}
// If I enable below blocks, I will see 307 response code in Fiddler.
/*
conn.connect();
int responseCode = conn.getResponseCode();
Log.d("TEST_JSON", "Code: " + String.valueOf(responseCode));
*/
Log.d("TEST_JSON", "Finish sending JSON.");
conn.disconnect();
}
catch (IOException e)
{
Log.e("TEST_JSON",e.getMessage()); // <<-- No error from this try catch block.
}
I tried and still cannot figure out why JsonWriter didn't trigger to my WCF (I attached my WCF to my localhost service, only Fiddler direct POST will hit the break point in my WCF project while Android App didn't reach to it). I follow the exact example from Android Developer site though. I google and didn't find any site on using JsonWriter with OutputStreamWriter (I saw some post using StringWriter).
May I know where did my code wrong ?

Based on this StackOverFlow post WCF has a 'Thing' about URI, I managed to solve this issue.
All I need is to make sure my POST web service has URI Template ends with "Slash".
Example: http://10.72.137.98/myWebSvc/posvctFun/
Instead of http://10.72.137.98/myWebSvc/postFun

Related

How to call a Youtube Data API through HTTPUrlConnection in Android with using headers?

I am trying to develop a part of my app in which i want to get video details for a keyword. I am using the search list API. I think I have an issue with the authorization. I am getting a 401. I have tried passing my authorization details.
I have tried the following code after going through a few resources online and I am current getting the java.io.FileNotFoundException at the line at which i get the Input Stream. The connection code that I am getting is a 401.
The given code is in the doInBackground of an AsyncTask.
String ytres="";
URL url;
HttpURLConnection urlConnection = null;
try {
Log.d("youtubedata","a1");
url = new URL("https://www.googleapis.com/youtube/v3/search?part=id&q=queen%20bohemian");
Log.d("youtubedata","a2");
Log.d("youtubedata","a");
urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty ("Authorization", "Bearer MYAPIKEY");
urlConnection.setRequestProperty ("Accept", "application/json");
Log.d("youtubedatanum",Integer.toString(urlConnection.getResponseCode()));
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
ytres=ytres+current;
System.out.print(current);
}
Log.d("youtubedata",ytres);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return ytres;
I do suspect the issue is in the way i have passed my API Key.
Please go through the API docs at Calling the API and at Search Endpoint.
You'll see that your URL does not contain the needed API key passed on as the key parameter.
It may also worth it to dug up Google's own sample Java implementation at Search.java. However, that code, due to the layer of library abstraction it uses, is not of immediate help since it obscures the way a client should work directly with the API.
For You-tube Data API error 401
Possible issue for unauthorized (401) can be
authorizationRequired
youtubeSignupRequired
Check You-tube Data API error doc Here.
Also confirm that you have follow THIS steps to integrate API.
Sample API Code you can find Here
Hope this can help you.

How to Use Both HTTPS and HTTP to parse JSON data in Android?

I followed this to Parse Json In Android
I have Successfully Done it with HttpData handler..
Here I am Successfully Posting Data to server and Getting Response..
Now I want to Use this same in the Part of HTTPS..
Can Any one suggest me How to do this Without Major Changes in my code.. Because In my application I am doing this for more activities.. Please Suggest me to Use HTTPs in my code..
I will provide Additional Info... Depending Responses...
Update
In my code I have Changed HttpURLConnection to HttpsURLConnection
Please suggest me How to through this error In my code..
Update 1
I have Changed Certificate on server side.. Now its working On Https..
But Now,
I want to Use HTTP and HTTPS Both in one app Depending on Client Requirement So here now its worked with Https....
But I also need to work with Http
In my Code Can any any one suggest me...I want I should Work with Https and Http Both In one App.
to use both HTTP and HTTPS, you need to have the 2 methods (i think you already have them)
GetHTTPData(String urlString)
GetHTTPSData(String urlString)
now in HTTPDataHandler class (where you have both methods above)
you need to create a 3rd method GetDataFromUrl(), that will check URL and decide which method to use (http or https)
public String GetDataFromUrl(String url){
if(url.toLowerCase().startsWith("https")){
//HTTPS:
return GetHTTPSData(url);
}else{
//HTTP:
return GetHTTPData(url);
}
}
now in the AsyncTask class ProcessJSON
replace this line stream = hh.GetHTTPData(urlString);
with this one stream = hh.GetDataFromUrl(urlString);
if you don't want to add that 3rd method in HTTPDataHandler, just use the if-statement in ProcessJSON at doInBackground() to call either one of the 2 methods (http or https)
You can use HttpsURLConnection, replace HttpURLConnection by HttpsURLConnection .
public String GetHTTPData(String urlString){
try{
URL url = new URL(urlString);
HttpsURLConnection urlConnection =(HttpsURLConnection)url.openConnection();
// Check the connection status
if(urlConnection.getResponseCode() == 200)
{
// if response code = 200 ok
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
// Read the BufferedInputStream
BufferedReader r = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
sb.append(line);
}
stream = sb.toString();
// End reading...............
// Disconnect the HttpURLConnection
urlConnection.disconnect();
}
else
{
// Do something
}
}catch (MalformedURLException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally {
}
// Return the data from specified url
return stream;
}
What I understand is in your server side, they used self signed SSL certificate. So you have to install that certificate in your android device also. Settings > Security > install form storage.But for production build you have to buy ssl certificate from CA Authorities.
Hope this will solve your problem.
Remove HttpDataHandler lines in doInBackground use HttpUrlConnection directly in doInBackground or use HttpUrlConnection in JSONparse class to post params to server follow this tutorial to post params Website

Android keeping connection alive to receive constant data update from server

i hope you can help me with my problem. I have to instantiate an http connection and do a get call to the server.
After this call i have to check periodically if the server sent me some data (the connection must not be closed after the first data received). If it does, then i have to parse this data and pass it to an activity and wait again.
My problem is to understand if i'm doing correctly this thing. Here my code
try {
URL url = getUrl();
URLConnection urlConn = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) urlConn;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
while(true) {
sleep(5000);
int responseCode = httpConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = httpConnection.getInputStream();
String response = null;
if(inputStream.available() > 0) {
long length = inputStream.available();
byte[] bytes = new byte[(int) length];
inputStream.read(bytes);
response = new String(bytes, "UTF-8");
}
}
}
} catch(Exception e) {
e.printStackTrace();
}
getUrl() function gives me the complete url that i have to call.
Then i connect through httpConnection.connect();.
while i'm iterating is the connection already opend and capable of receiving incoming data?
I apologize for my english. Thanks a lot
Francesco
From the official android documentation
Uses of this class follow a pattern:
Obtain a new HttpURLConnection by calling URL.openConnection() and
casting the result to HttpURLConnection.
Prepare the request. The
primary property of a request is its URI. Request headers may also
include metadata such as credentials, preferred content types, and
session cookies.
Optionally upload a request body. Instances must be
configured with setDoOutput(true) if they include a request body.
Transmit data by writing to the stream returned by getOutputStream().
Read the response. Response headers typically include metadata such as
the response body's content type and length, modified dates and
session cookies. The response body may be read from the stream
returned by getInputStream(). If the response has no body, that method
returns an empty stream.
Disconnect. Once the response body has been
read, the HttpURLConnection should be closed by calling disconnect().
Disconnecting releases the resources held by a connection so they may
be closed or reused.
As you see from this quote, if you need to send some data to a host you just need to call setDoOutput(true) and use OutputStream of your connection to send data to the host. In this case you use "POST" request method after you called setDoOutput(true). If you don't need to send data, but just to connect to the host and retrieve data, you also don't need to call setRequestMethod("GET"), because it's default request method.
When you connect to the host, just use InputStream to get data from it.

Data from Android App -> SQL server

I'm developing an android application which is to collect data and then send it to a web directory.
So lets say a want to collect an array of data on the phone, and then after clicking a button send it all to the online directory as a file or stream. It does not even need to get a response - although in the future a confirmation would be handy.
Here is a guess at the sort of order of things...
dir = "someurl.com/data/files_received";
Array data;
sendDataSomehow(dir, data); //obv the difficult bit!
I am in very early stages of developing for Android although I have a lot of experience coding web so that bit will be fine.
I have found suggestions for things such as JSON, Google GSON, HTTP POST and GET - do these sound like the right track?
I hope I have been clear enough.
Yep, JSON would be a good solution for this.
Encode your array as JSON and then send it to your web server as the body of an HTTP POST request. If you have an hour to kill, here's a really good video from Google IO last year explaining how to implement a REST client on Android (what you're doing isn't strictly REST-ful, but the calls you make to the server are very similer): http://www.google.com/events/io/2010/sessions/developing-RESTful-android-apps.html
Right, just wanted to do a quick thank for putting me on the right track. Just had one of those THE CODE WORKS EUREKA moments, very happy. I haven't used JSON but I have managed to pass a variable from Android to SQL through a HTTP-POST and little bit of PHP.
I'm sure this is not the recommended ideology for many reasons although for prototype and presentation it will do just fine!
Here is the code for android:
try {
URL url = new URL("http://www.yourwebsite.com/php_script.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStream out = conn.getOutputStream();
Writer writer = new OutputStreamWriter(out, "UTF-8");
writer.write("stringToPass=I'd like to pass this");
writer.close();
out.close();
if(conn.getResponseCode() != 200)
{
throw new IOException(conn.getResponseMessage());
}
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null)
{
sb.append(line);
}
rd.close();
conn.disconnect();
} catch (MalformedURLException e1) {
textBox.setText(e1.toString());
} catch (IOException e2) {
textBox.setText(e2.toString());
}
And here is the code for the PHP:
$conn = mysql_connect("localhost","web108-table","********") or die (mysql_error());
mysql_select_db("web108-table",$conn) or die (mysql_error());
$str = $_POST['stringToPass'];
mysql_query("INSERT INTO table(field) VALUES ($str)");
This code works, very simple. Next tests will be to find out if it is suitable for a large number of strings.
I hope this is helpful to somebody else.

Does Android Support a server made on ashx or ASP.NET Web Handler file

I have an android application that have to communicate with the server using post method in HTTP. My application work fine whenever i open some other sites having basic page may be html or others but whenever i want to open my server file it gives nothing even though with get method in HTTP.
The blank response from the server can be understandable that what i am getting because i have to send some headers with post method as a request and ashx will send some response to it.
But still as expected by get method in HTTP the basic information of the page have to be retrieved.
for eg. my server url is http://172.17.3.90/RMALite/RLHandler.ashx
and the basic response from the get method have to be like this.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv=Content-Type content="text/html; charset=windows-1252"></HEAD>
<BODY></BODY></HTML>
Unfortunately i am getting nothing
but whenever i changed the url to open other sites it work fine and i got the response in text html format.
So my Question is, Android require some stuff to handle ASP.NET handler or ashx file as compare to other sites or URL's?
I know it late now but other can get benefit. Below is code snippet which help me to get accomplished same issue.
public static String excutePost(String targetURL, String urlParameters) {
//targetURL =http://172.17.3.90/RMALite/RLHandler.ashx
URL url;
HttpURLConnection connection = null;
try {
// Create connection
url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", ""
+ Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setRequestProperty("method-name", "parameter-value");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
// // Send request
DataOutputStream wr = new DataOutputStream(connection
.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
String field1 = connection.getHeaderField("field1");
String field2 = connection.getHeaderField("field2");
return anyArray;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
I believe it would be helpful n much appreciated to this post
thanks much
-y

Categories

Resources