I am using the below code for fetching data from live server...
try
{
var httpReq = (HttpWebRequest)HttpWebRequest.Create(new Uri(url_builder.ToString()));
httpReq.BeginGetResponse((ar) =>
{
var request = (HttpWebRequest)ar.AsyncState;
using (var response = (HttpWebResponse)request.EndGetResponse(ar))
{
//Enter Code here............................
response.Close();
}
});
}, httpReq);
}
catch (Exception ex)
{
Global.EmailExceptionMessage(ex);
}
And getting inner exception i.e.
Inner Exception: at System.Net.WebConnection.HandleError(WebExceptionStatus st, System.Exception e, System.String where)
at System.Net.WebConnection.ReadDone(IAsyncResult result)
You can try this one code to get httpresponse.
HttpWebRequest request = WebRequest.Create("http://google.com") as HttpWebRequest;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
WebHeaderCollection header = response.Headers;
var encoding = ASCIIEncoding.ASCII;
using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
{
string responseText = reader.ReadToEnd();
}
Related
I'm trying to call a website from my android watch but the thread exits (The thread 0x5 has exited with code 0 (0x0)) without a result.
I added the permissions "Internet" and "Network_state", which does not change the result. Below my code (done in Tizen and pure Xamarin):
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.activity_main);
textView = FindViewById<TextView>(Resource.Id.text);
Button mybtn = FindViewById<Button>(Resource.Id.btnCal);
SetAmbientEnabled();
try
{
mybtn.Click += delegate
{
Task<string> callTask = calculateRoute();
callTask.Wait();
string astr = callTask.Result;
};
}
catch (Exception ex)
{
string tt = ex.ToString();
}
}
private async Task<string> calculateRoute()
{
HttpClient client;
try
{
String RestUrl = "https://www.google.com";
var uri = new Uri(string.Format(RestUrl, string.Empty));
client = new System.Net.Http.HttpClient();
var response = await client.GetAsync(uri);
var content = await response.Content.ReadAsStringAsync();
return content;
}
catch (Exception ex)
{
string tt = ex.ToString();
return "";
}
}
Do you have any idea?
Thanks, Jeppen
After quite some research I found the solution thanks to: https://github.com/Samsung/Tizen-CSharp-Samples/tree/master/Wearable
Give the app the following permissions:
<privilege>http://tizen.org/privilege/internet</privilege>
<privilege>http://tizen.org/privilege/network.get</privilege>
<privilege>http://tizen.org/privilege/download</privilege>
C# code
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.google.lu");
//get the data
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string tt = ((HttpWebResponse)response).StatusDescription + "\n";
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
Happy coding, Jeppen
I have rest api designed in Slim 3. which stores the customer details in MySQL db. I am using Retrofit 1.9 to connect to webservice. I am receiving server error 500 where as same request working fine in POSTMAN.
//using retrofit
RestAdapter adapter = new RestAdapter.Builder().setEndpoint(Config.CUSTOMER_URL).build();
RegisterCustomer api = adapter.create(RegisterCustomer.class);
api.registerCustomer(custName.toString(),
phoneNumber.toString(),
address.toString(),
Config.API_KEY, new Callback<retrofit.client.Response>() {
#Override
public void success(retrofit.client.Response result, retrofit.client.Response response) {
BufferedReader reader = null;
String output = "";
try {
reader = new BufferedReader(new InputStreamReader(result.getBody().in()));
output = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
Log.d("customer result",result.getBody()+"##"+result.getStatus() +"##" +response.getBody().toString());
}
#Override
public void failure(RetrofitError error) {
Log.d("customer save fail ",error.getMessage());
}
});
Interface:
public interface RegisterCustomer
{
#FormUrlEncoded
#POST("/customer")
public void registerCustomer(
#Field("cust_name") String cust_name,
#Field("phone") String phone,
#Field("address") String address,
#Field("apikey") String apikey,
Callback<Response> callback);
}
My php code.
// Adding customer
// pass cust_name,phone,address and apikey
$app->post('/customer', function ($request, $response, $args) {
$_message = $request->getParsedBody();
$customer = new Customer();
$customer->cust_name = $_message['cust_name'];
$customer->phone = $_message['phone'];
$customer->address = $_message['address'];
$customer->apikey = $_message['apikey'];
$payload=[];
$customer->save();
if ($customer->id) {
$payload = ['cust_id' => $customer->id,
'cust_uri' => '/customer/' . $customer->id
];
return $response->withStatus(201)->withJson($payload);
}else {
return $response->withStatus(400);
}
});
i have issue with post request. Server gets me response message ok, but doesn't recognize json what i send as post body. I have tried almost everything. Php attribute $_POST is always empty.
Thank for your answers.
Json has structure :
{
"data": {
"email": "something#something.com",
"password": "tralala"
}
}
Android code :
public static Pair<Integer, String> signUpByEmailPost(String username, String passwd) {
try {
URL url = new URL(SERVER_URL + "create/createUser.php");
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setRequestMethod("POST");
urlConn.setRequestProperty("Content-Type", "application/json");
urlConn.setDoOutput(true);
urlConn.setDoInput(true);
urlConn.setUseCaches(false);
urlConn.connect();
JSONObject json = createJsonCredentials(username, passwd);
String dataString = json.toString();
Log.i(TAG, dataString);
OutputStreamWriter out = new OutputStreamWriter(urlConn.getOutputStream());
out.write(dataString);
out.flush();
int httpResult = resolveHttpResponseCode(urlConn);
if(httpResult > 0) {
return new Pair<>(httpResult, null);
}
String receivedDataString = getStringContentFromConnection(urlConn);
return new Pair<>(0, receivedDataString);
} catch (Exception e) {
e.printStackTrace();
}
return new Pair<>(3, null);
}
private static JSONObject createJsonCredentials(String username, String password) {
try {
JSONObject jsonInner = new JSONObject();
jsonInner.put("email", "something#something.com");
jsonInner.put("password", "tralala");
JSONObject jsonOuter = new JSONObject();
jsonOuter.put("data", jsonInner);
return jsonOuter;
} catch(JSONException ex) {
ex.printStackTrace();
}
return null;
}
Server response :
{
success: false,
errors: {
email: "blank_email",
password: "blank_password"
}
}
Server side :
<?php
$data["post"] = $_POST;
$email = $_POST["data"]["email"];
$password = $_POST["data"]["password"];
if(empty($email)) {
$errors['email'] = 'blank_email';
}
if(empty($password)) {
$errors['password'] = 'blank_password';
}
echo json_encode($data);
?>
Hi here you are returning null value from your method. Try this code. It will work.
private static JSONObject createJsonCredentials(String username, String password) {
JSONObject jsonOuter = new JSONObject();
try {
JSONObject jsonInner = new JSONObject();
jsonInner.put("email", "something#something.com");
jsonInner.put("password", "tralala");
jsonOuter.put("data", jsonInner);
} catch(JSONException ex) {
ex.printStackTrace();
}
return jsonOuter;
}
I am making an android application witch gets informations from a Web Service. I need a solution for parsing this result:
<Client xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://lmggroup.net/">
<ID>12805</ID>
<PersonalNumber>0</PersonalNumber>
<EntryDate>2013-01-28T14:39:01</EntryDate>
<FirstName>0</FirstName>
<LastName>0</LastName>
<Address>0</Address>
<Phone>0601231569</Phone>
<Email>aaa#aaa.com</Email>
<OrganizationalUnitID>02901</OrganizationalUnitID>
<Password>aaaaaa</Password>
<IsActive>true</IsActive>
</Client>
I've try this to solve this problem using the following code
public static ArrayList<UserContent> getUserContentList(String response)
{
ArrayList<UserContent> result = new ArrayList<UserContent>();
if (response != null && response.equals("") == false)
{
KXmlParser xmlParser = new KXmlParser();
Document xmlDoc = new Document();
ByteArrayInputStream bin = new ByteArrayInputStream(response.getBytes());
InputStreamReader isr = new InputStreamReader( bin );
try
{
xmlParser.setInput(isr);
xmlDoc.parse(xmlParser);
Element xmlRoot = xmlDoc.getRootElement();
if(xmlRoot != null)
{
Element[] xmlChild = XmlParser.getChildren(xmlRoot);
for ( int index = 0; index < xmlChild.length; ++index )
{
UserContent item = new UserContent();
Element[] contentNodes = XmlParser.getChildren(xmlChild[index]);
for ( int i = 0; i < contentNodes.length; ++i )
{
if (contentNodes[i].getName().equals(StaticStrings.contentUserID))
{
item.id = contentNodes[i].getText(0);
}
else if (contentNodes[i].getName().equals(StaticStrings.contentUserPIB))
{
item.pib = contentNodes[i].getText(0);
}
else if (contentNodes[i].getName().equals(StaticStrings.contentUserPhone))
{
item.phone = contentNodes[i].getText(0);
}
else if (contentNodes[i].getName().equals(StaticStrings.contentUserMail))
{
item.email = contentNodes[i].getText(0);
}
}
result.add(item);
}
}
}
catch (IOException e)
{
Log.e(TAG, e.getMessage());
}
catch (XmlPullParserException e)
{
Log.e(TAG, e.getMessage());
}
try
{
isr.close();
}
catch (IOException e) {}
}
return result;
}
But when I call this method, I get all the xml tags but their content is null.
a more straightforward way might be to use an XML serialization framework. if you were using pure Java that might be JAXB, but for Android Simple XML is a good choice. it a nutshell, you create a POJO then annotate it indicate how you want to serialize / deserialize. for example,
#Root(name = "Client")
class Client {
#Attribute(name = "ID")
private String id;
...
}
then to deserialize,
Serializer serializer = new Persister();
String xml = ...; // get your XML into a string, or a stream
Client client = serializer.read(Client.class, xml);
i did a simple Web Service in Java and i deployed it in JBOSS 5.1.
This WS handles C2DM service for sending a notify message to an Android phone. I set all like i red in google c2dm api, and, first of all, i sign up for accessing to c2dm service. In this case, all works well.
Now i have to do the same in .NET on IIS7. Some clarification about the .Net code:
setRegId() and pushMessage() method are available by WebService.
handShakeRegId() is simply called by setRegId() after String "reg_id" and "device_id" are setted
all code commented are my try for solving problem, but all was useless
Thats the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Net;
using System.Text;
using System.IO;
using System.Diagnostics;
namespace WebService1
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class Service1 : System.Web.Services.WebService
{
private String accountType = "HOSTED_OR_GOOGLE";
private String email = "example#gmail.com";
private String password = "password";
private String service = "ac2dm";
private String source = "com.cloudTest.app";
private String HTTPHeaderCT = "application/x-www-form-urlencoded";
private String auth;
private String reg_Id;
private String deviceId;
private String collapseKey = "CollapseKey";
public void handShakeRegId()
{
HttpWebRequest req;
Stream reqst;
try
{
req = (HttpWebRequest)WebRequest.Create(#"https://www.google.com/accounts/ClientLogin");
// string proxy = null;
// req.MaximumAutomaticRedirections = 4;
// req.MaximumResponseHeadersLength = 4;
// req.Credentials = CredentialCache.DefaultCredentials;
string data = String.Format("accountType={0}&Email={1}&Passwd={2}&service={3}&source={4}", accountType, email, password, service, source);
byte[] buffer = Encoding.UTF8.GetBytes(data);
// ASCIIEncoding encoding = new ASCIIEncoding();
// byte[] buffer = encoding.GetBytes(data);
req.Method = "POST";
req.ContentType = HTTPHeaderCT;
req.ContentLength = buffer.Length;
// req.Proxy = new WebProxy(proxy, true);
// req.CookieContainer = new CookieContainer();
reqst = req.GetRequestStream(); // add form data to request stream
reqst.Write(buffer, 0, buffer.Length);
}
catch (Exception e)
{
Debug.WriteLine("--------------------");
Debug.Write("(handShakeRegId) Request Error:" + e);
Debug.WriteLine("--------------------");
throw;
}
HttpWebResponse res;
Stream resst;
try
{
res = (HttpWebResponse)req.GetResponse();
resst = res.GetResponseStream();
StreamReader sr = new StreamReader(resst, Encoding.UTF8);
string response = sr.ReadToEnd();
string SID = response.Substring((response.IndexOf("SID=") + 4),
(response.IndexOf("\n") - 4));//extracting SID
string Auth = response.Substring((response.IndexOf("Auth=") + 5),
(response.Length - (response.IndexOf("Auth=") + 5)) - 1);//extracting Auth
auth = Auth;
}
catch (Exception e)
{
Debug.Write("(handShakeRegId) Response Error:" + e);
throw;
}
resst.Flush();
resst.Close();
reqst.Flush();
reqst.Close();
}
[WebMethod]
public void setRegId(String reg_id, String device_id)
{
reg_Id = reg_id;
deviceId = device_id;
Debug.WriteLine("RegID=" + reg_Id);
Debug.WriteLine("--------------------");
Debug.WriteLine("DeviceID=" + deviceId);
handShakeRegId();
}
[WebMethod]
public void pushMessage(String msg)
{
// Needed! Without an SSL Exception comes out
System.Net.ServicePointManager.ServerCertificateValidationCallback += delegate(object sender,
System.Security.Cryptography.X509Certificates.X509Certificate certificate,
System.Security.Cryptography.X509Certificates.X509Chain chain,
System.Net.Security.SslPolicyErrors sslPolicyErrors) { return true; };
HttpWebRequest req;
Stream reqst;
try
{
req = (HttpWebRequest)WebRequest.Create("http://android.apis.google.com/c2dm/send");
//req.MaximumAutomaticRedirections = 4;
//req.MaximumResponseHeadersLength = 4;
//req.Credentials = CredentialCache.DefaultCredentials;
//req.Credentials = new NetworkCredential("example#gmail.com","password");
//req.KeepAlive = true;
//string proxy = null;
string data = String.Format("registration_id={0}&collapse_key={1}&data.message={2}", reg_Id, collapseKey, msg);
// ASCIIEncoding encoding = new ASCIIEncoding();
// byte[] buffer = encoding.GetBytes(data);
byte[] buffer = Encoding.UTF8.GetBytes(data);
req.Method = "POST";
req.ContentType = HTTPHeaderCT;
req.ContentLength = buffer.Length;
req.Headers.Add("Authorization", "GoogleLogin auth=" + auth);
// req.Proxy = new WebProxy(proxy, true);
// req.CookieContainer = new CookieContainer();
reqst = req.GetRequestStream(); // add form data to request stream
reqst.Write(buffer, 0, buffer.Length);
}
catch (Exception e)
{
Debug.Write("(PushMessageMsgOUT)Error: " + e);
throw;
}
HttpWebResponse res;
Stream resst;
try
{
res = (HttpWebResponse)req.GetResponse();
HttpStatusCode responseCode = ((HttpWebResponse)res).StatusCode;
if (responseCode.Equals(HttpStatusCode.Unauthorized) || responseCode.Equals(HttpStatusCode.Forbidden))
{
Debug.WriteLine("Unauthorized - need new token");
}
else if (!responseCode.Equals(HttpStatusCode.OK))
{
Debug.WriteLine("Response from web service not OK :");
Debug.WriteLine(((HttpWebResponse)res).StatusDescription);
}
resst = res.GetResponseStream();
StreamReader sr = new StreamReader(resst);
string response = sr.ReadToEnd();
}
catch (Exception e)
{
Debug.WriteLine("(pushMessageMsgIN) Error: "+e);
throw;
}
resst.Flush();
resst.Close();
reqst.Flush();
reqst.Close();
}
}
}
Handshake method works well! I get auth token without problem.
setRegId method is called by Android device (in my case is the Android+GoogleApi 2.2 emulator)
Error which comes out is always the same in pushMessage getResponse() ( and its strange because i implement connection exactly like its in handshake method :-/ ):
A first chance exception of type 'System.Net.WebException' occurred in System.dll
(pushMessageMsgIN) Error: System.Net.WebException: remote server error (401) Unauthorized in System.Net.HttpWebRequest.GetResponse()
2 days for searching something useful but.... NOTHING!!
Its very stressful...
I hope someone can help me.
I red something about Authentication in IIS, so i enabled Anonymous User and other unknown things just for trying. Nothing!
Solved: MY STUPIDITY !!! i made a mistake in private String source !! I specified a wrong package name! -.-