I just want to check whethere the user entered url is valid or not so far what i have tried is HTTPurl connection am getting the result but response time is very slow how to make it speed up let me post my code :
public Boolean Netwrok(String str) {
HttpURLConnection connection = null;
try {
URL myUrl = new URL(str);
connection = (HttpURLConnection) myUrl.openConnection();
connection.setRequestProperty("Accept-Encoding", "identity");
InputStream response = connection.getInputStream();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
connection.disconnect();
}
}
This is what am trying now am trying to make it with volley am getting response but don't know how to validate it can anybody helpmeout:
Let me post my volley code:
RequestQueue queue = Volley.newRequestQueue(getContext());
String str_url = getEditText().getText().toString();
str_url = s;
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, s,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
Intent intent = new Intent(getContext(), LoginActivity.class);
getContext().startActivity(intent);
// mTextView.setText("Response is: "+ response.substring(0,500));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
setDialogMessage("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
can anybody tell any solution for my prob
Android has pre-build Patterns for WEB_URL which you can use as:-
if (Patterns.WEB_URL.matcher(serverURL).matches() == false){
//Invalid
}else{
//valid
//In here you can also put one more check by opening connection to URL and check for HTTP_RESPONSE_OK (200) then url is FINE.
}
try below way, just change code in onErrorResponse method of volley request
StringRequest stringRequest = new StringRequest(Request.Method.GET, s,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//setDialogMessage("That didn't work!");
// NOT VALID URL
NetworkResponse networkResponse = error.networkResponse;
if (networkResponse.statusCode != 200) {
Log.e("Status code", String.valueOf(networkResponse.statusCode));
//code 404: for page not found, you can read about more responce code in link below
}
}
});
more about http status code
Related
I'm trying to show a token from one website on my mobile phone. I'm using the Volley to send a GET request, but I get no response (networkResponse == null). My code is fine because I can connect f.e. to google. I found that maybe the website's response comes after the execution of a program.
How can I slow down the execution or how can I enforce waiting for the response? Or maybe can I do something else? Also, the website that I'm trying to connect works well because I can execute the request using Postman. Any ideas how to resolve it are also appreciated.
My code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = (TextView) findViewById(R.id.codeC);
TextView textView2 = (TextView) findViewById(R.id.blad);
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://ec2-3-15-216-171.us-east-2.compute.amazonaws.com:3000/pairing";
// String url ="https://google.com";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
textView.setText("Response is: " + response.substring(0, 130));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error == null) {
textView2.setText("error1");
return;
}
if (error.networkResponse == null) {
textView2.setText("error2");
return;
}
String body;
//get status code here
final String statusCode = String.valueOf(error.networkResponse.statusCode);
//get response body and parse with appropriate encoding
try {
body = new String(error.networkResponse.data, "UTF-8");
textView2.setText(body);
} catch (UnsupportedEncodingException e) {
// exception
textView2.setText("bbb");
}
}
});
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
500000,
1,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(stringRequest);
}
}
I want to get json response from local server. I want to add port in that. how to add port while using volley in android
In main activity
{
String url = "192.2.3.1:80/data";
sendAndRequestResponse(url, new VolleyCallback(){
#Override
public void onSuccess(JSONObject result){
}
});
}
private void sendAndRequestResponse(final String url, final VolleyCallback callback) {
//RequestQueue initialized
mRequestQueue = Volley.newRequestQueue(MainActivity.this, new ProxyPort());
//String Request initialized
mStringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(getApplicationContext(), "Response :" + response.toString(), Toast.LENGTH_LONG).show();//display the response on screen
Log.e("url", url);
Log.e("Response", response.toString());
try {
JSONObject obj = new JSONObject(response);
callback.onSuccess(obj);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("ERR", "Error :" + error.toString());
}
});
VolleyLog.DEBUG = true;
mRequestQueue.add(mStringRequest);
}
I want to add port in this url. I want to access local host using ip. How to achieve it
I had 2 pages: first one is login page and second is category page. In login API after entering the credentials, I am getting the response as sesssion id from response header.
The sesssion id will be saved and it will use for further API calls. I am trying to call second API (category page). In this page, as an input am passing the saved session id in the request header. Getting response as "session expired". Also tried to pass Set-Cookie: PHPSESSID=d9f9sdkfjs9 in the request header. but it didn't work.
Note :
I am experiencing this issue in production environment only (SSL included)
I am using volley library for handling APIs.
public void fnCallLoginAPI() {
try {
//DEMO URL
//final String URL="http://demo.io/api/api.php?m=login";
//LIVE URL
final String URL = "https://www.live.com/shop/api/api.php?m=login";
final String requestBody = "email=abc.b#xyz.com" + "&password=43443==" + "&strPlatform=i" + "&strDeviceToken=null";
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
String strResponse = response;
System.out.println("THE RESPONSE IS in PROFILE IS" + response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
})
{
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Cookie", "PHPSESSID=" + sessionID);
return headers;
}
#Override
public byte[] getBody() throws AuthFailureError {
byte[] body = new byte[0];
try {
System.out.println("THE REQIEST BODY IS" + requestBody);
body = requestBody.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
Log.e("TAG", "Unable to gets bytes from JSON", e.fillInStackTrace());
}
return body;
}
};
AppApplication.getInstance().addToRequestQueue(stringRequest, "assignment");
} catch (Exception e) {
}
}
public void fnCallCateGoryAPI(){
try { final String URL ="https://www.live.com/shop/api/api.php?m=getcategories";
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
String strResponse = response;
System.out.println("THE RESPONSE IS in PROFILE IS" + response);
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject(strResponse);
sessionID = jsonObj.optString("session_id");
System.out.print("sessionID" + sessionID);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
})
{
};
AppApplication.getInstance().addToRequestQueue(stringRequest, "assignment");
} catch (Exception e) {}
}}
#fazil try after increasing the token expiration time from the backend
#fazil : I was facing something similar in my projects too and the reason i understood was actually due to multiple header values set under same key "Set-Cookie".
Please do check this in your logs.
Also, make sure that you have set the headers properly in your request(check the logs of request and response from your Server).
If everything implemented is correct and the issue is due to multiple values in the same header you need to check this implementation of volley : https://github.com/georgiecasey/android-volley-duplicateheadersfix
I have already integrated volley library working good with JSON. Now am trying to access WCF SOAP I do not know how to pass XML string as request and how to get XML string as response.
// Tag used to cancel the request
String tag_string_req = "string_req";
//String url = "URL......";
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
StringRequest strReq = new StringRequest(Request.Method.POST,
url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
pDialog.hide();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
pDialog.hide();
}
}){
#Override
public String getBodyContentType() {
return "application/xml; charset=" +
getParamsEncoding();
}
#Override
public byte[] getBody() throws AuthFailureError {
String postData = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
"<sampletag>\n" +
"\t<sampletag>data</sampletag>\n" +
"</sampletag>"; // TODO get your final output
try {
return postData == null ? null :
postData.getBytes(getParamsEncoding());
} catch (UnsupportedEncodingException uee) {
// TODO consider if some other action should be taken
return null;
}
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
You can use the String request of Volley. The String request returns a string which can you parse using XMLReader
StringRequest req = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
processDataUsingXMLReader(reponse);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// handle error response
}
}
);
Volley does not have any XML Request, checkout the official documentation: https://android.googlesource.com/platform/frameworks/volley/+/android-4.3_r0.9/src/com/android/volley/toolbox/
There are two ways you can do it:
Method 1
So, you will have to fetch the raw String using StringRequest and then parse it.
Code:
StringRequest request = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// now, convert response (String) to XML
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
//error
}
}
);
queue.add(request);
To convert String to XML:
You can try Simple-XML, it is a XML Marshaling Tool. Link : http://simple.sourceforge.net/download.php
Sample code (string to xml using Simple) :
Serializer serializer = new Persister();
serializer.read(Pojo.class, response);
Method 2
Try this Volley Adapter Class : https://gist.github.com/itsalif/6149365
It also does the same, using Simple-XML to serialize XML Objects without your coding effort.
Assuming you want to parse XML data using Android Volley from the String response, you can achieve this by converting the response to an InputStream using ByteArrayInputStream, as follows:
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
XMLParser xmlParser = new XMLParser();
InputStream inputStream = new
ByteArrayInputStream(response.getBytes("UTF-8"));
List<YourObject> object = new ArrayList<>();
object.addAll(xmlParser.parseFeed(inputStream));
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
This example simply demonstrates parsing an RSS feed and storing an array of objects in a List, which is demonstrated in greater detail here.
I am trying to fire a DELETE request using HttpUrlConnection in android,I am setting the setRequestmethod as DELETE and getting a 200 as response code. The Item is not getting deleted. The async I am using is below.
private class DeleteTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = null;
URL url = null;
try {
url = new URL(urls[0]);
Log.i("URL to access :", urls[0]);
} catch (MalformedURLException exception) {
exception.printStackTrace();
}
HttpURLConnection httpURLConnection = null;
try {
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("DELETE");
httpURLConnection.setRequestProperty("charset", "utf-8");
httpURLConnection.setUseCaches(false);
System.out.println("ResponseCode: "+httpURLConnection.getResponseCode());
if(httpURLConnection.getResponseCode() == 204){
Log.d(TAG,"Deleted");
}
} catch (IOException exception) {
exception.printStackTrace();
} finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
return null;
}
}
}
It looks like the setRequestMethod() is not working and its taking the Request as a GET and giving me a 200 !!
I tested this in postman(a chrome extension) and it was working fine , If it was a backend issue then from postman also it should fail.
okHttp:
I was trying to make this work on okHttp also for that
Request request = new Request.Builder().url(url.toString()).patch(body).build();
How will I make up this for delete, because delete request dosent have a body
Volly:
I've tried out the google volly library too..
RequestQueue requestQueue = Volley.newRequestQueue(TimerSummary.this);
StringRequest request = new StringRequest(Request.Method.DELETE, uri, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG,"Response: "+response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG,"Error: "+error);
}
});
requestQueue.add(request);
This also returns like GET request, I am getting the item as json which was supposed to be deleted.
any suggestions are appreciated.
Thanks in advance..
It was actually a typo!!! I am an idiot!Both of my methods work fine ,but I am Now using Google's volly library for network related things.
I was missing a "/" before the "?" before appending parameters with the URL