I just started the topic to get data from a JSON OpenData and visualize via my phone.
I followed this tutorial and it has worked all :)
https://www.learn2crack.com/2013/10/android-asynctask-json-parsing-example.html
The url whew i get the datas is :
http:// + api.learn2crack.com/android/json/ (sorry for that, I don't have a good reputation :) )
Then I wanted to try a Opendata me and my android application stops, the url is:
http://ckan.opendata.nets.upf.edu/storage/f/2013-11-30T16%3A49%3A59.118Z/london.json
You can see it's the same and I only change the name of URL in the code.
You know if the problem is because of the OpenData? and I need some permission? Because when I execute the second part my app stopped
Here, this will work. I am using Strict Policy but normally you should use Async. Please google this as to why we should use Async instead of Strict Policy. This is irrelevant here
When i am using HttpPost to get your json from url, i am getting these errors :-
405 Method Not Allowed
The method POST is not allowed for this resource.
You cannot POST a file
so i am using HttpGet :-
String url = "http://ckan.opendata.nets.upf.edu/storage/f/2013-11-30T16:49:59.118Z/london.json";
try{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
//HttpPost httpPost = new HttpPost(url);
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.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();
JSONObject jObj = new JSONObject(sb.toString());
JSONArray json2 = json.getJSONArray("user");
for (int i = 0; i < json2.length(); i++) {
JSONObject c = json2.getJSONObject(i);
}
}
catch (Exception e) {
e.printStackTrace();
}
Related
Will HTTP post request cause 500 internal server ERROR?. hmmm if so below is my code and why am i constantly getting 500 Internal server error? what am i missing in the code?.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost((GetAllNewsURL));
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
1);
nameValuePairs.add(new BasicNameValuePair("pageNo", "0"));
nameValuePairs.add(new BasicNameValuePair("newsPerPage",
"0"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
stream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(stream));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
thanks,
for me sometimes because of problem on server side I have to send params as header try the same thing like
HttpPost httppost = new HttpPost((GetAllNewsURL+"?pageNo=0&newsPerPage=0"));
or only pass one param as header hopefully it works
I am trying to get a list of user subreddits via the reddit api. Currently I am able to do a post for login which returns a cookie and modhash. Those are the parameters I'm passing to my method below. However each time I call the function I get an empty response:
"{}"
How can I pass a cookie and modhash via HTTPGET to get a valid response?
public void getUserSubreddits(String[] loginInfo){
HttpClient client = new DefaultHttpClient();
URL url = null;
try {
url = new URL("http://www.reddit.com/subreddits/mine/.json?limit=100");
HttpGet httpGet = new HttpGet(String.valueOf(url));
client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, System.getProperty("http.agent"));
httpGet.addHeader("cookie", loginInfo[1]);
httpGet.addHeader("modhash", loginInfo[0]);
HttpResponse response = client.execute(httpGet);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
InputStream is = buf.getContent();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
Log.d(TAG,total.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
It was a simple mistake. To anyone in the future trying this I solved the problem by using Chrome to inspect the headers of an active session on http://www.reddit.com/subreddits/mine/.json?limit=100 url and found that the cookie header started with:
reddit_session
So I removed the modhash changed the my header parameter to read:
httpGet.addHeader("cookie", "reddit_session="+loginInfo[1]+";");
With this I got a valid response.
I'm coding a login system which will keep the user permanently logged on (until username or password is incorrect) but I'm having an issue with cookie storage. What I want to do is have the cookies store in local storage (probably shared preference). Though I have no idea where to start. This is my main HTTP Post function.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
// Add your data
httppost.setHeader("X-Requested-With", "XMLHttpRequest");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
StringBuffer sb = new StringBuffer();
BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent()));
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
return sb.toString();
} catch (Exception e) {
//TODO: WIP
e.printStackTrace();
}
I want to set the cookies first (of course if there are any) then I would like to resave them after the httppost has executed. Where can I go about doing this?
Edit there is about 4 cookies that are saved.
This should help you get started:
http://docs.oracle.com/javase/tutorial/networking/cookies/definition.html
Check out this post as well:
https://stackoverflow.com/a/3587332/2495131
I am trying to upload an image to server.For that I have added jar files like apache-mime4j,http client,httpcore and httpmime.
And my code is as follows..
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
MultipartEntity multiPart = new MultipartEntity();
multiPart.addPart("my_picture", new FileBody(new File(imagePath.toString())));
httpPost.setEntity(multiPart);
HttpResponse res = httpClient.execute(httpPost);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String json = reader.readLine();
JSONTokener tokener = new JSONTokener(json);
JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
JSONArray data = object.getJSONArray("data");
System.out.println("posted finalResult"+data);
if (responseEntity != null) {
responseEntity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
The problem is that I am getting an error at the line
multiPart.addPart("my_picture", new FileBody(new File(imagePath.toString())));
And on clicking that error I am getting "Configure build path".
Anyone please tell me what is wrong in my code.
Thanx in advance.
I Use BufferedInputStream For HTTP POST/GET
But I Get Some Error the Below
java.io.FileNotFoundException: http://XX.XX.XX.XX/WebWS/data.aspx
Transport endpoint is not connected
Why Get This Error. My Code is Below
URL url = new URL(glob.postUrl);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
try {
httpConn.setDoInput(true);
httpConn.setDoOutput(true);
httpConn.setRequestMethod("GET");
httpConn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
httpConn.setRequestProperty("Content-Language", "TR");
httpConn.setConnectTimeout(12000);
Iterator<String> reqProps = hMap.keySet().iterator();
while (reqProps.hasNext()) {
String key = reqProps.next();
String value = hMap.get(key);
httpConn.addRequestProperty(key, value);
}
InputStream in = new BufferedInputStream(httpConn.getInputStream());
StringBuilder builder = new StringBuilder();
String line;
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(in, "UTF-8"));
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} finally {
in.close();
}
httpConn.disconnect();
Thanks.
Is there any reason you're not using HttpClient?
You can replace your code with something like:
HttpContext httpContext = new BasicHttpContext();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = httpClient.execute(httpGet, httpContext);
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
String page = EntityUtils.toString(entity);
You can setup the HttpClient with ClientConnectionManager and HttpParams for security and various http parameters for the client at initialisation (plenty of examples around if you search on class names).
HttpURLConnectionImpl.getInputStream() is known to throw a FileNotFoundException if the HTTP response status code is 400 or higher, i.e. for any error condition on the server side. You should check what the status code really is in order to obtain suitable debug information.
However, I second Mark Fisher's suggestion about using HttpClient, which AFAIK is the preferred way of working with HTTP on Android.