I have a ComClass for windows phone 8 that post and read data from a url.
public class ComClass
{
private string _url = """;
private string _postdata = "";
public Boolean data_received;
public string data;
public ComClass(string url, string data2send)
{
_url = url;
_postdata = data2send;
}
public void Send()
{
data_received = false;
HttpWebRequest request = null;
request = (HttpWebRequest)WebRequest.Create(_url);
request.ContentType = "application/json;charset=UTF-8";
request.Method = "POST";
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
}
private void GetRequestStreamCallback(IAsyncResult asyncResult)
{
HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
Stream postStream = request.EndGetRequestStream(asyncResult);
byte[] byteArray = Encoding.UTF8.GetBytes(_postdata.ToString());
postStream.Write(byteArray, 0, _postdata.Length);
postStream.Dispose();
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
private void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
data = streamRead.ReadToEnd();
data_received = true;
streamResponse.Dispose();
streamRead.Dispose();
response.Dispose();
}
catch (WebException ex)
{
data = ex.Message;
data_received = false;
//using (StreamReader reader = new StreamReader(ex.Response.GetResponseStream()))
//{
// //Debug.WriteLine("Exception output : " + ex);
//}
}
}
}
The class works fine. My problem is that i want somehow to get notified that i have a response. eg
ComClass ccc = null;
private void Button_Click(object sender, RoutedEventArgs e)
{
try
{
ccc = new ComClass("url", "somedata");
ccc.Send();
//while (ccc.data_received == false)
//{ }
string itemdata = ccc.data;
//do something with itemdata...
}
catch (Exception ee)
{
}
}
I know that i must use await or delegates but i am stuck...
Related
I have a problem using Volley. want to use POST method with some parameters and get Array type response but my response is not an array type. Here, I share my request code and response.
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest postRequest = new StringRequest(Request.Method.POST, "https://umrahtech.com/umrahtechapi.php",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// response
Log.d("Response", response);
route = null;
route_spinner.setSelection(0);
check_in_date = null;
check_out_date = null;
adults = child = room = child1 = child2 = child3 = child4 = child5 = 0;
text_adults.setText("0 Adult");
text_child.setText("0 Child");
text_room.setText("0 Room");
layout_child.setVisibility(View.GONE);
in_date.setText("Add Date");
out_date.setText("Add Date");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("case", "hotel_makkah");
params.put("location", route);
params.put("check_in_1", check_in_date);
params.put("check_out_1", check_out_date);
params.put("passengers", room_array.toString());
return params;
}
};
queue.add(postRequest);
when u use string request response you get will be string also.
you should turn that response to JsonArray , then get bojects from that JsonArray something like this :
if (response != null) {
JSONArray fetchlist = JSONArray(response);
for (int i=0 ; i<fetchlist .lenght ; i++) {
JSONObject obj = fetchlist.getJSONObject(i);
Int idd = obj.getInt("genderid");
I have solved this question in this way. Where hudx_Object and hudx_JSON is JSONObject
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest hudxconnect = new StringRequest(Request.Method.POST, "https://umrahtech.com/umrahtechapi.php",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
hudx_Object = new JSONObject(response);
if (hudx_Object != null) {
hudx_JSON = hudx_Object.getJSONObject("response");
hudx_Object = new JSONObject(hudx_JSON.toString());
} else {
hudx_Object = null;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
progressDialog.dismiss();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("case", "hotel_makkah");
params.put("location", route);
params.put("check_in_1", check_in_date);
params.put("check_out_1", check_out_date);
params.put("passengers", room_array.toString());
return params;
}
};
I've made this code to download this JSON:
private void rxPublishProgress()
{
final OkHttpClient mOkHttpClient = new OkHttpClient();
final Request mRequest = new Request.Builder().url(AirportService.SERVICE_ENDPOINT).build();
Observable.create(new Observable.OnSubscribe<String>()
{
#Override
public void call(Subscriber<? super String> subscriber)
{
try {
InputStream inputStream;
okhttp3.Response response = mOkHttpClient.newCall(mRequest).execute();
if (response.isSuccessful())
{
inputStream = response.body().byteStream();
long len = response.body().contentLength();
String progress = "0";
subscriber.onNext(progress);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
byte[] data = new byte[1024];
long total = 0;
int count;
String line = null;
final int bufferSize = 1024;
boolean flag = false;
JSONObject jsonObject = null;
final char[] buffer = new char[bufferSize];
final StringBuilder out = new StringBuilder();
Reader in = new InputStreamReader(inputStream, "UTF-8");
for(;flag ==false ;)
{
count = in.read(buffer, 0, buffer.length);
if (count == -1)
{
progress = "100";
subscriber.onNext(progress);
flag = true;
}
else
{
out.append(buffer, 0, count);
// Log.d("out",out.toString());
total += count;
progress = String.valueOf(total * 100 / len);
subscriber.onNext(progress);
}
}
inputStream.close();
// try parse the string to a JSON object
try
{
jsonObject = new JSONObject(out.toString());
}
catch (JSONException e)
{
e.printStackTrace();
}
Log.d("lengt",String.valueOf(jsonObject.length()));
subscriber.onCompleted();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).subscribeOn(Schedulers.newThread()).subscribe(new Subscriber<String>() {
#Override
public void onCompleted()
{
Log.d("Complete","complete");
}
#Override
public void onError(Throwable e)
{
}
#Override
public void onNext(final String progress) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run()
{
percentage.setText(progress+"%");
}
});
}
});
and it works, but I don't know how to retrieve this JSON or to convert with GSON.
I need to retrieve the percentage of download because it's a specific request of this project, but I need also the JSONObject or the List . How could I do to have this?
Thanks
As i got you have 1 Observable and you need:
1) display percentage
2) do something else
So you can do like this:
Observable<okhttp3.Response> responseObservable = Observable.create(/*your code to return response*/)
.subscribeOn(Schedulers.newThread())
.replay(1)
.refCount();
responseObservable
.map(toPercents())
.subscribe(displayPercents());
responseObservable
.map(toSomethingElse())
.subscribe(displaySomethingElse());
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "http://jsonplaceholder.typicode.com/posts";
//JSON Node Names
// private static final String TAG_OS = "Employee";
private static final String TAG_USER= "userId";
private static final String TAG_NAME = "id";
private static final String TAG_TITLE = "title";
private static final String TAG_BODY = "body";
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
ver = (TextView)findViewById(R.id.user);
name = (TextView)findViewById(R.id.id);
api = (TextView)findViewById(R.id.titile);
body =(TextView)findViewById(R.id.body);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json.getJSONArray("");
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String ver = c.getString(TAG_USER);
String name = c.getString(TAG_NAME);
String api = c.getString(TAG_TITLE);
String body =c.getString(TAG_BODY);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_USER, ver);
map.put(TAG_NAME, name);
map.put(TAG_TITLE, api);
map.put(TAG_BODY, body);
list.add(map);
List=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, list,
R.layout.list_v,
new String[] { TAG_USER,TAG_NAME, TAG_TITLE,TAG_BODY }, new int[] {
R.id.user,R.id.id, R.id.titile,R.id.body});
List.setAdapter(adapter);
List.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+list.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
json parse:-
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Logcat here
java.lang.NullPointerException: Attempt to invoke virtual method 'org.json.JSONArrayorg.json.JSONObject.getJSONArray(java.lang.String)' on a null object reference
at com.example.mind.sqlitedatabase.MainActivity$JSONParse.onPostExecute(MainActivity.java:134)
at com.example.mind.sqlitedatabase.MainActivity$JSONParse.onPostExecute(MainActivity.java:103)
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Actually, I faced problem when I click get button to call uri for json parsing.
But when in android device json = null parsing...
Here I used Volley library, it handle the all the things which you did manually(Asynctask, httprequest for json).
I hope it may helps you
// JsonObject request
public void getJSONFromUrl(String url) {
RequestQueue queue = Volley.newRequestQueue(getActivity());
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Response", "Response" + response);
//handle the json response
handleResponse(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error", "Error: " + error.getMessage());
}
});
queue.add(jsonObjReq);
}
// converting from json to Map using JsonHelper class
public void handleResponse(JSONObject response) {
Map<String, Object> map = new HashMap<>();
if(response != null){
try {
// JsonObject to Map
map = JsonHelper.toMap(response);
// boolean isSuccess = map.get("success")
// if(isSuccess){
//}
if (map.size() != 0){
// use the data
}
Log.d("MAp","map" + map);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
here below class will help converting json response to MAP, from map to json.
copied from https://gist.github.com/codebutler/2339666
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.*;
public class JsonHelper {
public static Object toJSON(Object object) throws JSONException {
if (object instanceof Map) {
JSONObject json = new JSONObject();
Map map = (Map) object;
for (Object key : map.keySet()) {
json.put(key.toString(), toJSON(map.get(key)));
}
return json;
} else if (object instanceof Iterable) {
JSONArray json = new JSONArray();
for (Object value : ((Iterable)object)) {
json.put(value);
}
return json;
} else {
return object;
}
}
public static boolean isEmptyObject(JSONObject object) {
return object.names() == null;
}
public static Map<String, Object> getMap(JSONObject object, String key) throws JSONException {
return toMap(object.getJSONObject(key));
}
public static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap();
Iterator keys = object.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
map.put(key, fromJson(object.get(key)));
}
return map;
}
public static List toList(JSONArray array) throws JSONException {
List list = new ArrayList();
for (int i = 0; i < array.length(); i++) {
list.add(fromJson(array.get(i)));
}
return list;
}
private static Object fromJson(Object json) throws JSONException {
if (json == JSONObject.NULL) {
return null;
} else if (json instanceof JSONObject) {
return toMap((JSONObject) json);
} else if (json instanceof JSONArray) {
return toList((JSONArray) json);
} else {
return json;
}
}
}
volley library usage
http://www.androidhive.info/2014/09/android-json-parsing-using-volley/
I've a requirement. I have a working POST call ("http://localhost:8080/POSTAPI/table/testmaster/create"). I sent JSON data through postman and details got inserted into MySQL database. Now i'm trying to send the json data through apache httpcleint. but, it failed to insert into mysql database.
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost("http://localhost:8080/POSTAPI/table/testmaster/create");
JSONObject testmaster = new JSONObject();
testmaster.put("testRunId", testRunId);
testmaster.put("testClassName", className);
testmaster.put("testMethod", methodName);
testmaster.put("createdBy", "leela");
testmaster.put("createdDate", startDate);
testmaster.put("lastUpdatedBy", "raghu");
testmaster.put("lastUpdatedDate", endDate);
testmaster.put("attribute1", "methodName");
testmaster.put("attribute1Value",methodName );
testmaster.put("attribute2", "result");
testmaster.put("attribute2Value", successResult);
testmaster.put("attribute3", "Test Suite");
testmaster.put("attribute3Value", suiteName);
testmaster.put("attribute4", "test group");
testmaster.put("attribute4Value", TestGroup);
testmaster.put("attribute5", "dataprovider");
testmaster.put("attribute5Value", dataProvider);
StringEntity stringEntity = new StringEntity(testmaster.toString());
post.setEntity(stringEntity);
post.setHeader("Accept", "application/json");
post.setHeader("Content-type", "application/json");
CloseableHttpResponse response = client.execute(post);
System.out.println("Status: "+response.getStatusLine());
This is what i tried. if anybody have any idea of post operation through httpclient or any other alternative please let me know. Thanks in advance.
Use the following code :
private class postJsonData extends AsyncTask<Void, Integer, Boolean> {
ProgressDialog dialog;
String responseString = null;
private postJsonData() {
super();
dialog = new ProgressDialog(MainActivity.this);
this.dialog.setTitle("Please wait.");
this.dialog.setCancelable(false);
this.dialog.show();
}
#Override
protected void onPreExecute() {
dialog.setProgress(0);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
// Making progress bar visible
if (this.dialog.isShowing()) {
dialog.setProgress(progress[0]);
}
}
#SuppressWarnings("deprecation")
#Override
protected Boolean doInBackground(Void... params) {
Boolean result=false;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.2.2/android/jsonpost.php");
try {
JSONObject testmaster = new JSONObject();
try {
testmaster.put("testRunId", "1");
testmaster.put("testClassName", "className");
testmaster.put("testMethod", "methodName");
testmaster.put("createdBy", "leela");
testmaster.put("createdDate", "startDate");
} catch (JSONException e) {
e.printStackTrace();
}
List<NameValuePair> nameValuePairs = new ArrayList<>();
nameValuePairs.add(new BasicNameValuePair("json_string", testmaster.toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
result = false;
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
result = false;
}
} catch (final ClientProtocolException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"ClientProtocolException : " + e.toString(),
Toast.LENGTH_LONG)
.show();
}
});
result = false;
} catch (final IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"IOException : " + e.toString(),
Toast.LENGTH_LONG)
.show();
}
});
result = false;
}
return result;
}
#Override
protected void onPostExecute(final Boolean success) {
//progressBar.setVisibility(View.GONE);
if (dialog.isShowing()){
dialog.dismiss();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Response from Server: " + responseString ,
Toast.LENGTH_LONG)
.show();
}
});
if (success){
}else{
}
super.onPostExecute(success);
}
}
Here is my php code which accepts the json string and decode into array.
<?php
if (empty($_POST['json_string'])) {
echo "Empty json data";
exit;
}else{
$json_string = $_POST['json_string'];
}
$params = array();
$params = json_decode($json_string,true);
//echo $params['testClassName'];
var_dump($params);
?>
I want to send JSON from desktop application to the server with mvc wepApi.
this is my desktop application code ,that convert data to the JSON and send it.
private void btnAddUserType_Click(object sender, EventArgs e)
{
UserType userType = new UserType();
userType.UserTypeName = txtUserTypeName.Text;
string json = JsonConvert.SerializeObject(userType);
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:3852/api/default1");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream());
streamWriter.Write(json);
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
var streamReader = new StreamReader(httpResponse.GetResponseStream());
var responseText = streamReader.ReadToEnd();
}
and this is my web api
// POST api/default1
public void Post([FromBody]string value)
{
UserTypeRepository bl = new UserTypeRepository();
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(UserType));
MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(value));
UserType u = new UserType();
u = (UserType)js.ReadObject(stream);
bl.Add(u);
}
but when post api is calling the Value is null.
why?
using(var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
streamWriter.Write(json);
You are not flushing nor closing the stream, so basically the data never gets to the api.
My code:
Program.cs - Console App
class Program
{
static void Main(string[] args)
{
var user = new UserModel {Id = 4, FirstName = "Michael", LastName = "Angelo"};
var json = JsonConvert.SerializeObject(user);
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:56506/api/Values/");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using(var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
streamWriter.Write(json);
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
var streamReader = new StreamReader(httpResponse.GetResponseStream());
var responseText = streamReader.ReadToEnd();
Console.WriteLine(responseText);
Console.ReadKey();
}
}
UserModel.cs - some data class
public class UserModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Id { get; set; }
}
ValuesController.cs - WebApi controller from template
public class ValuesController : ApiController
{
// GET api/values
public UserModel[] Get()
{
return UserProvider.Instance.Get(); // returns some test data
}
// GET api/values/5
public UserModel Get(int id)
{
return new UserModel{Id=1,FirstName="John",LastName="Smith"};
}
// POST api/values
public void Post([FromBody]UserModel value)
{
if (value == null) // BREAKPOINT HERE, just to see what's in value
{
var x = value;
}
}
}
WebApiConfig.cs - default config with added line about Json, but IT WORKS WITHOUT IT -it's so that I can test GET easily in browser etc. ;)
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Result: