Internet request works the first time, but not on subsequent requests - java

On the first request it goes to the internet and retrieves the data. When I try it again, it just gives me the data that is already in the inputstream. How do I clear the cached data, so that it does a new request each time?
This is my code:
InputStreamReader in = null;
in = new InputStreamReader(url.openStream());
response = readFully(in);
url.openStream().close();

Recreate the URL object each time.

You can create a URLConnection and explicitly set the caching policy:
final URLConnection conn = (URLConnection)url.openConnection();
conn.setUseCaches(false); // Don't use a cached copy.
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
See The Android URLConnection documentation for more details.

HttpClient API might be useful
address = "http://google.com"
String html = "";
HttpClient httpClient = DefaultHttpClient();
HttpGet httpget = new HttpGet(address);
BufferedReader in = null;
HttpResponse response = null;
response = httpClient.execute(httpget);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.seperator");
while ((l = in.readLine()) != null) {
sb.append(l + nl);
}
in.close();
html = sb.toString();
You'll need to catch some exceptions

Related

How to use HttpURLConnection in Android to post data?

I want to send json data via stream to the server, but I struggle to make it work.
I have the following method:
String data = "{\"id\":\"2633\",\"f_name\":\"Test\",\"l_name\":\"Aplikace\",\"city\":\"Nymburk\",\"address\":\"Testovaci 123456789 xyz\",\"psc\":\"288 02\"}";
private String httpPost(String urlString, String data, String session_per) {
StringBuffer sb = new StringBuffer("");
String s1 = "";
try {
URL url = new URL(urlString);
String s2 = "";
HttpURLConnection httpurlconnection = (HttpURLConnection)url.openConnection();
httpurlconnection.setDoInput(true);
httpurlconnection.setDoOutput(true);
httpurlconnection.setUseCaches(false);
httpurlconnection.setRequestMethod("POST");
httpurlconnection.setRequestProperty("Cookie",session_per);
httpurlconnection.setRequestProperty("Authentication-Token", GlobalVar.KLIC);
httpurlconnection.setRequestProperty("Content-type", "application/json");
httpurlconnection.setAllowUserInteraction(false);
OutputStreamWriter outStrWrt = new OutputStreamWriter(httpurlconnection.getOutputStream());
outStrWrt.write(data);
outStrWrt.close();
String s3 = httpurlconnection.getResponseMessage();
//dataoutputstream.flush();
//dataoutputstream.close();
InputStream inputstream = httpurlconnection.getInputStream();
String line = "";
BufferedReader br = new BufferedReader(new InputStreamReader(inputstream));
int i;
while( (line = br.readLine()) != null) {
sb.append(line);
}
s1 = sb.toString();
}
catch(Exception ex)
{
ex.printStackTrace();
s1 = "";
}
return s1;
}
Can anyone tell me why this won't work? The cookies etc. are all correct. Did I miss something important? This is like the 6th method I am trying and I'm starting to get desperate :D
Thank you!
EDIT:
It succesfully connects and the server responds, but it doesn't update user data, as if the json didn't get to the server correctly.
If my Java code is correct there may be a server-side issue.
Try to use flush() method,you don't close this output stream before you read all bytes
outStrWrt.flush();
InputStream inputstream=httpurlconnection.getInputStream();
If you use Java 11, you can try to use HttpClient too.
E.g:
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder().uri(new URI(urlString)).header("Cookie",session_per).header("Authentication-Token",GlobalVar.KLIC).header("Content-type","application/json").POST(HttpRequest.BodyPublishers.ofString(data)).build();
String datas=client.send(request,BodyHandlers.ofString());
return datas;

405 - method not allowed calling web service from struts

I have a data access object which calls a web service. In my browser I can hit the web service using a url and it is successful.
http://mycompany:9080/ReportingManager/service/repManHealth/importHistoryTrafficLightStatus.json
But when try to execute the code below in my data access object I get a 405 error saying method not allowed.
String requestURI = "http://mycompany:9080/ReportingManager/service/repManHealth/importHistoryTrafficLightStatus.json";
URL url = new URL(requestURI);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("GET");
httpCon.setRequestProperty("Accept", "application/json");
OutputStreamWriter out = new OutputStreamWriter(
httpCon.getOutputStream());
int responseCode = httpCon.getResponseCode();
String responseMessage = httpCon.getResponseMessage();
BufferedReader rd = new BufferedReader(new InputStreamReader(httpCon.getInputStream()));
StringBuffer sb = new StringBuffer();
String line = null;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
String jsonResponse = sb.toString();
out.close();
httpCon.disconnect();
Can someone help me with what might be wrong here?
Also maybe there is a better way to execute a web service to an external application and read the response using struts? Or do people think this method is okay?
thanks
If u are using GET method. Try the below code.
string url = String.Format("http://somedomain.com/samplerequest?greeting={0}",param);
WebClient serviceRequest = new WebClient();
serviceRequest.Headers[HttpRequestHeader.ContentType] = "application/json";
string response = serviceRequest.DownloadString(new Uri(url));
Thanks for your ideas however non of them were quite right. I fixed the 405 using the code below...
String requestURI = "http://myserver:9080/ReportingManager/service/repManHealth/importHistoryTrafficLightStatus.json";
URL url = new URL(requestURI);
URLConnection conn = url.openConnection();
InputStream in = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(in));
StringBuffer sb = new StringBuffer();
String line = null;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
By calling httpCon.getOutputStream()); you're not sending a HTTP GET anymore, but a HTTP POST.
Note: This is under the assumption you end up getting the implementation provided by Sun. Which will change GET to POST for backwards compatibility.

Corrupted Json in Android Eclipse

im having a strange problem when receiving json results from the server. I have no idea what the problem is. The thing is that my String json result is corrupted, with strange symbols.
The result is like this (taken from eclipse debug)
Image :
Another strange thing that happens is that when I change the URL of the service to an alternative one, it works and the data is not corrupted. The URLs are the same but once redirects everything to the other.
The URL is use always is (example) http://www.hello.com
The URL that works is http://www.hello.com.uy
(cant post the exact link for security reasons)
The second one redirects everything to the first one, its the only thing it does.
I have tried changing the encoding to UTF-8 and it is still not working, here is the code (with one of the URLs commented)
I have also tried using Dev HTTP Client extension from chrome to check the service and it works fine, no corrupted data. Also, it works perfectly on iOS so i think its just and android/java issue.
DevClient:
try {
JSONObject json = new JSONObject();
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 10000);
HttpClient client = new DefaultHttpClient(httpParams);
//String url = TAG_BASEURL_REST +"Sucursal";
String url = "http://www.-------.com/rest/Sucursal";
//String url = "http://www.--------.com.uy/rest/Sucursal";
HttpGet request = new HttpGet(url);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream is = entity.getContent();
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();
String jsonRes = sb.toString();
JSONArray jObj = new JSONArray(jsonRes);
return jObj;
}
} catch (Throwable t) {
Log.i("Error", "Request failed: " + t.toString(), t);
}
return null;
InputStream is = entity.getContent();
// check if the response is gzipped
Header encoding = response.getFirstHeader("Content-Encoding");
if (encoding != null && encoding.getValue().equals("gzip")) {
is = new GZIPInputStream(is);
}

Incomplete content (buffer) of webpage

I want to read the content of a webpage with the following methods, but I only get 60-70 percent of it.
I've tried 2 different methods to read the webpage, both with the same result. I also tried different Urls. I get no errors or timeouts.
What I am doing wrong ?
URL url = new URL(uri.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try
{
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null)
{
sb.append(line + "\n");
}
br.close();
this.content = sb.toString();
}
finally
{
urlConnection.disconnect();
}
AND
HttpGet get = new HttpGet(uri);
HttpClient defaultHttp = new DefaultHttpClient(httpParameters);
HttpResponse response = defaultHttp.execute(get);
StatusLine status = response.getStatusLine();
if(status.getStatusCode() == HttpStatus.SC_OK)
{
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
String encoding = "utf-8";
//long length = entity.getContentLength();
//if(entity.getContentEncoding() != null)
//{
// encoding = entity.getContentEncoding().getValue();
//}
//if(length > 0)
//{
byte[] buffer = new byte[1024];
long read = 0;
do
{
read = stream.read(buffer);
if(read > 0)
{
this.content += new String(buffer, encoding);
}
}while(read > 0);
//}
}
#edit
I've tried it with C# and WinForms. I read the complete html source of that webpage.
With java-android it doesn't work.
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://www.kicker.de");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string content = reader.ReadToEnd();
reader.Close();
response.Close();
the httpurlconnection in apache's util jar has limited the biggest bytes in a response, i couldn't remember the number of it.
But in most of time ,may you use the http conncetion in UI thread , so sometimes it's not safe,and maybe will be killed, you can choose to deal with the http request in a thread but not the UI thread. So I want to know if you do it in the UT thread
I have currently the same Problem. I tried my Code in a simple Java Application and I receive the whole content. But on Android, the Content is incomplete. This Question is now a year old. I guess you have solved it in the meantime. Can you please add your Solution?
Edit:
I wrote the content into a File on my Android Device. The Content was complete!
It seems logcat doesn´t show the complete Output you receive from the Devie.

Android Java strange issue building URL

So I'm building an URL to be called to get a JSON response but facing a strange issue. Building the URL as shown below returns "Not found" but for testing purposes I just built the URL as such "http://api.themoviedb.org/3/search/person?api_key=XXX&query=brad" and didn't append anything and that returned the correct response. Also tried not encoding "text" and same thing...Not found. Any ideas?
StringBuilder url = new StringBuilder();
url.append("http://api.themoviedb.org/3/search/person?api_key=XXX&query=").append(URLEncoder.encode(text, ENCODING));
Log.v("URL", url.toString());
try {
HttpGet httpRequest = null;
httpRequest = new HttpGet(url.toString());
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
InputStream input = bufHttpEntity.getContent();
String result = toString(input);
//JSONObject json = new JSONObject(result);
return result;
Try using the code I have below. I've copied and pasted it out of some code I use and I know it works. May not solve your problem but I think its worth a shot. I've edited it a little bit and it should just be copy and paste into your code now.
HttpGet request = new HttpGet(new URI(url.toString()));
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(request);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
JSONObject jResponse = new JSONObject(builder.toString());

Categories

Resources