In this URL I have a JSON tree that I wish to retrieve as a String so I can use the library I implemented JSON by amirdew. This is the code I have to parse the JSON:
String simpleJsonString = url;
JSON json = new JSON(simpleJsonString);
String firstTag = json.key("extract").index(0).stringValue();
txtinfo.setText(firstTag);
I've tried using HttpsRequest but I couldn't make it:
HttpResponse httpResponse = null;
try {
httpResponse = httpClient.execute(httpPost);
} catch (IOException e) {
e.printStackTrace();
}
HttpEntity httpEntity = httpResponse.getEntity();
try {
is = httpEntity.getContent();
} 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");
System.out.println(line);
}
is.close();
json = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
You are getting an NetworkOnMainThreadException exception because you are trying to make an API call on the UI or Main thread. One shouldn't do any long running operations on UI thread as it is only intended for UI operations. You should either make an API call in AsyncTask or usesSome networking library like Volley or Retrofit.
Check this out for the detailed description of the exception you mentioned.
AsyncTask Implementation Of your code
private class DownloadFilesTask extends AsyncTask<URL, Integer, String> {
protected Long doInBackground(URL... urls) {
HttpResponse httpResponse = null;
try {
httpResponse = httpClient.execute(httpPost);
} catch (IOException e) {
e.printStackTrace();
}
HttpEntity httpEntity = httpResponse.getEntity();
try {
is = httpEntity.getContent();
} 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");
System.out.println(line);
}
is.close();
return sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
showDialog("Downloaded ");
}
}
Hope it helps.
Try this code..
Best way to used retrofit for api calling ..
add below depedency into app level gradle file..
implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
after that make retrofit object like this way..
public class ApiClient {
private final static String BASE_URL = "https://en.wikipedia.org/w/";
public static ApiClient apiClient;
private Retrofit retrofit = null;
public static ApiClient getInstance() {
if (apiClient == null) {
apiClient = new ApiClient();
}
return apiClient;
}
//private static Retrofit storeRetrofit = null;
public Retrofit getClient() {
return getClient(null);
}
private Retrofit getClient(final Context context) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.readTimeout(60, TimeUnit.SECONDS);
client.writeTimeout(60, TimeUnit.SECONDS);
client.connectTimeout(60, TimeUnit.SECONDS);
client.addInterceptor(interceptor);
client.addInterceptor(new Interceptor() {
#Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request();
return chain.proceed(request);
}
});
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client.build())
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit;
}
}
after that define all api that you want to call..
public interface ApiInterface {
#GET("api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=Portugal")
Call<Response> getData();
}
after that in activity call..
ApiInterface apiInterface = ApiClient.getInstance().getClient().create(ApiInterface.class);
Call<Response> responseCall=apiInterface.getData();
responseCall.enqueue(new Callback<Response>() {
#Override
public void onResponse(Call<Response> call, Response<Response> response) {
if (response.isSuccessful() && response.body()!=null && response!=null){
Gson gson=new Gson();
String data=gson.toJson(response.body());
}
}
#Override
public void onFailure(Call<Response> call, Throwable t) {
}
});
Related
I have a problem with connecting to WAMP server with my android program that I made with eclipse....
This is my class:
public class Webservice {
public static String readurl(String url)
{
try {
HttpClient client = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
HttpResponse response = client.execute(method);
InputStream inputStream = response.getEntity().getContent();
String resault = ConvertInputStream(inputStream);
return resault;
}
catch (ClientProtocolException e) {
//e.printStackTrace();
Log.i("Log", "Protocol");
}
catch (IOException e) {
//e.printStackTrace();
Log.i("Log", "IOException");
}
return "read";
}
private static String ConvertInputStream(InputStream inputStream)
{
try
{
BufferedReader reader = new BufferedReader(new
InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
builder.append(line);
}
return builder.toString();
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
}
And this is my activity code:
public class NotesActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String resault = Webservice.readurl("http://localhost/note-server");
Log.i("Log", "Resault: " + resault);
When I run, it gives me "IOException" because of the "Log" in my class under the IOException, and at the end give me "Result: read"!!!!!
How can I fix that?
If you are running on an emulator then you should use 10.0.2.2 instead of localhost.
See this post.
I don't understand why can't I read this json link but Browser Chrome can read, I tried with different link and I read them.
this is the link for requesting json response:
My Code:
runOnUiThread(new Runnable() {
#Override
public void run() {
new sendToken().execute("http://admin:123#qlvb-snv.newsaigonsoft.com/push-notifications-portlet/api/secure/jsonws/pushnotificationsdevice/add-push-notifications-device?token=cNAXYNQSPHk:APA91bF86THzkPE_ol9euea1M40x6jVgN9RjUOISVtL-UEXDYpAP62aeRnUwkLrSt6z8C4saTJPKW5CJ57VSRmovZ5OBX4NsZg3U-zoDdXB64dWzAQGB7WllGvqGEO3Nt4_Fbg-vUyok&platform=android");
}
});
and My AsyncTask:
class sendToken extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
return docNoiDung_Tu_URL(params[0]);
}
#Override
protected void onPostExecute(String s) {
Log.d("Respones: ", s + "");
}
}
and it does not respond with anything.
Two things may be the cause
either your method
docNoiDung_Tu_URL is not correct or correctly written
or, You have no permissions to access Internet.
change your doInBackground Like this
class sendToken extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
HttpClient httpclient = getNewHttpClient();
HttpGet httpget = new HttpGet(arg0[0]);
// Execute HTTP get Request
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity, "UTF-8");
return responseString;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
Log.d("Respones: ", s);
}
Also add the dependencies to build.gradle
compile('org.apache.httpcomponents:httpcore:4.4.1') {
exclude group: 'org.apache.httpcomponents', module: 'httpclient'
}
don't forget to add the internet permission to manifest
<uses-permission android:name="android.permission.INTERNET"/>
you have to make http call
HttpURLConnection urlConnection = null;
String My_URL = "YOUR URL";
BufferedReader reader = null;
URL url = null;
String Json;
InputStreamReader inputStream1 = null;
InputStream inputStream = null;
inside do in background
#Override
protected String doInBackground(Void... params) {
try {
url = new URL(My_URL);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
if(urlConnection.getResponseCode() == 200)
{
inputStream = urlConnection.getInputStream();
Json = readData(inputStream);
}
else {
urlConnection.getResponseCode();
}
}catch (Exception e){
Json = e.toString();
}
finally {
if (urlConnection!=null)
urlConnection.disconnect();
try {
if (inputStream!=null)
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return Json;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
// your work
}
public String readData(InputStream inputStream)
{
StringBuilder builder = new StringBuilder();
try {
if (inputStream != null) {
inputStream1 = new InputStreamReader(inputStream);
reader = new BufferedReader(inputStream1);
String line = reader.readLine();
while (line != null) {
builder.append(line);
line = reader.readLine();
}
} else {
Toast.makeText(MainActivity.this, "errorwa", Toast.LENGTH_SHORT).show();
}
}catch (Exception e){}
return builder.toString();
}
You can not directly read the response from the url.
Try out below code:
public JSONObject getJSONFromUrl(String url) {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// 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;
}
Add the below permission in manifest
<uses-permission android:name="android.permission.INTERNET"/>
i want to get data from my server with AsyncTask and then extract some and send to another location and get more info from that
for first section I'm using from this code for run my AsyncTask method and Cancel AsyncTask after some time (for no response...)
new MySecendServer(link, param,mInstagramSession).execute();
final ProgressDialog pd2 = new ProgressDialog(testActivity.this);
pd2.show();
final Timer tm = new Timer();
tm.scheduleAtFixedRate(new TimerTask() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
count++;
if (count == 30) {
pd2.cancel();
tm.cancel();
new MySecendServer(.....) .cancel(true); }
}
});
}
}, 1, 1000);
then after get data from my server i try to get more info with this code but i don't get any response or exception i test this code in doInBackground And onPostExecute and no any diffrent and no any response
try {
String requestUrl = "https://api.instagram.com/v1/users/";
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(requestUrl);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity == null) {
throw new Exception("Request returns empty result");
}
InputStream stream = httpEntity.getContent();
String response = StringUtil.streamToString(stream);
if (httpResponse.getStatusLine().getStatusCode() != 200) {
throw new Exception(httpResponse.getStatusLine().getReasonPhrase());
}
} catch (Exception ex) {}
now anyone can give me reason or any suggest for do this work ?
thanks
Update :
I found exception here :
HttpResponse httpResponse = httpClient.execute(httpGet);
and message is :
cause NetworkOnMainThreadException (id=831620140512)
Update 2 :
My first AsyncTask
public class MySecendServerClass extends AsyncTask {
private String link="";
private String [][]pparams;
private InstagramUser IG_User;
private InstagramSession IG_Session;
public MySecendServerClass(String link,String [][]params,InstagramSession user){
this.link=link;
this.pparams=params;
this.IG_Session = user;
}
#Override
protected String doInBackground(Object... arg0) {
String data="";
try{
if(pparams!=null){
for(int i=0;i<pparams.length;i++){
if(i!=0){
data+="&";
}
data+=URLEncoder.encode(pparams[i][0],"UTF8")+"="+URLEncoder.encode(pparams[i][1],"UTF8");
}
}
URL mylink=new URL(link);
URLConnection connect=mylink.openConnection();
connect.setDoOutput(true);
OutputStreamWriter wr=new OutputStreamWriter(connect.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader=new BufferedReader(new InputStreamReader(connect.getInputStream()));
StringBuilder sb=new StringBuilder();
String line=null;
while((line=reader.readLine())!=null){
sb.append(line);
}
Log.d("sssss",sb.toString());
return sb.toString();
}
catch(Exception ex){
}
return null;
}
#Override
protected void onPostExecute(Object tr) {
super.onPostExecute(tr);
String result = (String)tr;
try{
JSONObject json = new JSONObject(result);
JSONArray jArray = json.getJSONArray("followlist");
JSONObject jObject = jArray.getJSONObject(0);
String client_id=jObject.getString("client_id");
GrtUserProfile(client_id);
}
catch(Exception ex){
}
}
}
Solve Problem With this Code :
public void GrtUserProfile(String Cid) {
String requestUrl= "https://api.instagram.com/v1/users/"+Cid+"/"+"&access_token="+mInstagramSession.getAccessToken();
new HTTPRequestClass().execute(requestUrl);
}
class HTTPRequestClass extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
try {
String url = urls[0];
HttpGet httpRequest = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(httpRequest);
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity == null) {
throw new Exception("Request returns empty result");
}
InputStream stream = httpEntity.getContent();
String response = StringUtil.streamToString(stream);
if (httpResponse.getStatusLine().getStatusCode() != 200) {
throw new Exception(httpResponse.getStatusLine().getReasonPhrase());
}
return response;
} catch (Exception e) {
return "";
}
}
protected void onPostExecute(String Response) {
Log.i("Response", Response);
}
}
Instead of using Timer to cancel async task you can set timeout for HttpURLConnection
private class DownloadFilesTask extends AsyncTask<URL, Integer, Boolean> {
protected Boolean doInBackground(URL... urls) {
try {
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
con.setRequestMethod("HEAD");
con.setConnectTimeout(5000); //set timeout to 5 seconds
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
} catch (java.net.SocketTimeoutException e) {
return false;
} catch (java.io.IOException e) {
return false;
}
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Boolean result) {
showDialog("Downloaded " + result );
}
}
I have an Android application that records an audio file and uploads it to an API for fingerprinting. The app works well when it uploads for the first time and gets the right response. However, on trying to upload again the request from the app seems to reach the server without the uploaded file. Strangely, when I close the app completely and open it again, it works well. However, I want it to be able to do the uploads continuously without having to close it after every attempt.
Here is my code:
public class MainActivity extends Activity {
class UploadFileTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... voids) {
String responseString = "";
HttpResponse response = null;
try {
//below is the API url
String url = "http://1**.**.**.**:8000/api/tag/";
File track = new File(Environment.getExternalStorageDirectory(), "mezzo.mp3");
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create();
reqEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
FileBody fb = new FileBody(track);
//InputStream inputStream = new ;
//reqEntity.addPart("track", fb);
reqEntity.addBinaryBody("track", track);
final HttpEntity myEntity = reqEntity.build();
httppost.setEntity(myEntity);
Log.i("request", String.valueOf(myEntity));
response = httpclient.execute(httppost);
//process response
responseString = new BasicResponseHandler().handleResponse(response);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null!=response)
{
try
{
HttpEntity httpEntity = response.getEntity();
if (null != httpEntity)
{
httpEntity.consumeContent();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
return responseString;
}
protected void onPostExecute(final String responseString) {
runOnUiThread(new Thread() {
public void run() {
Toast.makeText(getApplicationContext(),
responseString, Toast.LENGTH_LONG).show();
}
});
}
What I'm I doing wrong?
I am not sure but I suspect that the http response might not be consumed entirely.
Can you try consuming the response before you return from the function in a finally block:
finally
{
if (null!=response)
{
try
{
HttpEntity httpEntity = response.getEntity();
if (null != httpEntity)
{
httpEntity.consumeContent();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
I am extremely new to C# And windows app programming.
I am trying to create an AsyncTask, like in java , where i can query a url and get its response back.
Here is the code i usually use in java, i want to implement the copy in C sharp.
public interface ResponseCallback
{
void onSuccess(String response);
void onFailure(String exception);
}
public class MyAsyncTask extends AsyncTask<String, Void, String>
{
private ResponseCallback myResponse = null;
private int type = 0;//POST
List<NameValuePair> nameValuePairs = null;
StringEntity entity = null;
private HttpResponse response = null;
public MyAsyncTask(String url,ResponseCallback myResponse)
{
this.myResponse = myResponse;
this.execute(url);
}
#Override
protected String doInBackground(String... param)
{
String url = param[0];
response = null;
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter("http.connection-manager.timeout", 15000);
try {
if (type == 0)
{
HttpPost httppost = new HttpPost(url);
if (nameValuePairs != null)
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
if (entity != null)
httppost.setEntity(entity);
response = httpclient.execute(httppost);
}
else
{
HttpGet httppost = new HttpGet(url);
response = httpclient.execute(httppost);
}
} catch (ClientProtocolException es)
{
} catch (IOException e)
{
}
String resp = null;
if (response != null)
{
try {
resp = Utilities.convertStreamToString(response.getEntity().getContent());
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return resp;
}
else
return null;
}
#Override
protected void onPostExecute(String resp)
{
if (resp != null)
{
if (response.getStatusLine().getStatusCode() == Constants.RESULT_OK )
{
try {
myResponse.onSuccess(resp.trim());
} catch (IllegalStateException e) {
}
}
else
myResponse.onFailure(resp);
}
else
myResponse.onFailure(resp);
}
}
I have tried this in C #. Anyone wanna help me fix few things in this code and give me some info, what to do next
namespace The_Vow.Global
{
class MyAsyncTask
{
public ResponseCallback callback;
static void queryUrl(String url)
{
RunAsync(url).Wait();
}
static async Task RunAsync(String url)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("MY_IP");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP GET
HttpResponseMessage response = await client.GetAsync(url);
//response = await client.PostAsJsonAsync("api/products", gizmo);
if (response.IsSuccessStatusCode)
{
String jsonStr = await response.Content.ReadAsStringAsync();
// callback variable is not being recognized????
callback.onSuccess(jsonStr);
//Console.WriteLine("{0}\t${1}\t{2}", product.Name, product.Price, product.Category);
}
}
}
}
}
namespace The_Vow.Global
{
public interface ResponseCallback
{
void onSuccess(String response);
void onFailure(String exception);
}
}
Your callback field is an instance field, so you can't access it from a static method, unless you make the field static.
Another alternative I would like to recommend though, is not using a field at all. Pass the callback variable as a method argument.
Or you can stop using static methods at all, make them instance methods.