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());
Related
sender
StringBuilder builder = new StringBuilder();
HttpParams httpParameters=new BasicHttpParams();
HttpResponse response;
HttpPost httpPost = new HttpPost(address);
StringEntity entity = new StringEntity(JSON.toString(), HTTP.UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpClient client = new DefaultHttpClient(httpParameters);
response = client.execute(httpPost);
receiver
StringBuffer jb = new StringBuffer();
String line = null;
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
json_in = org.json.HTTP.toJSONObject(jb.toString());
JSONObject js=new JSONObject((String)json_in.get("Method"));
Map<String, String> dict = new HashMap<>();
Iterator it=js.keys();
while(it.hasNext()){
String key=(String)it.next();
dict.put(key,(String) js.get(key));
}
Hi, I'm trying to pass JSON using http post, The error comes from line JSONObject js=new JSONObject((String)json_in.get("Method"));
org.json.JSONException: Unterminated string at 314 [character 315 line 1]
How it can be fixed?
Thanks.
Edit:
this request is working without problems
curl http://localhost:8080/ --data "{'a':'b','image':'
/9j/4QAYRXhpZgAASUkqAAgAAAAAAAAAAAAAAP/sABFEdWNreQABAAQAAAA8AAD/4QMraHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLwA8P3hwYWNrZXQgYmVnaW49Iu+7vyIgaWQ9Ilc1TTBNcENlaGlIenJlU3pOVGN6a2M5ZCI/PiA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrPSJBZG9iZSBYTVAgQ29yZSA1LjAtYzA2MSA2NC4xNDA5NDksIDIwMTAvMTIvMDctMTA6NTc6MDEgICAgICAgICI+IDxyZGY6UkRGIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyI+IDxyZGY6RGVzY3JpcHRpb24gcmRmOmFib3V0PSIiIHhtbG5zOnhtcD0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLyIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bXA6Q3JlYXRvclRvb2w9IkFkb2JlIFBob3Rvc2hvcCBDUzUuMSBXaW5kb3dzIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOkVCODRFNkEyRDRBMjExRTBCMEFCRUMwRkU5QUY1ODY1IiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOkVCODRFNkEzRDRBMjExRTBCMEFCRUMwRkU5QUY1ODY1Ij4gPHhtcE1NOkRlcml2ZWRGcm9tIH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AQ5yf/2gAIAQMDAT8hbPBIydDPB0f/2gAMAwEAAhEDEQAAECKKez//2gAIAQEDAT8QcqibGJIIOgtEmhHLKXOStTftncTmtpthr9D8NlUyVmt3CFB2lWCkm/ict56Xzov/2gAIAQIDAT8QtIkinCI+g6SRM2tHRCGDODJT0f/aAAgBAwMBPxC4JRKCX0SkbRJ/DN4HjSOB/9k="}
I checked the JSON with a pretty-print formatter here and it shows the same error in your app.
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);
}
I have this request in Java but in the response i haven't all source, and Json object fail..
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(
"http://url?"+params);
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
String str = result.toString();
Document doc = Jsoup.parse(str);
JSONObject json = new JSONObject();
List<JSONObject> list = new ArrayList<JSONObject>();
Element elementsTable = doc.getElementById("shortlist");
this element shortlist can't find that..but if i go with my browser and get the source there is..where i'm wrong?
You can do it with Jsoup with simpler code ...
Connection connection = Jsoup.connect(url)
Document urlDoc = connection.get();
Elements domElement = urlDoc.getElementById(String id);
i've tried grabbing html source of this webapge http://www.mindef.gov.sg/content/imindef/press_room/official_releases/nr/2013/jan/22jan13_nr.html . however i encounted error as it responded with a different type of html as compared to what i am able to see from the browser. it seems like doing a httopost to the web and on the app result in different type of respond
address="http://www.mindef.gov.sg/content/imindef/press_room/official_releases/nr/2013/jan/22jan13_nr.html";
String result = "";
HttpClient httpclient = new DefaultHttpClient();
// httpclient.getParams().setParameter("http.protocol.single-cookie-header", true);
HttpProtocolParams.setUserAgent(httpclient.getParams(), "Mozilla/5.0 (Linux; U; Android 2.2.1; en-ca; LG-P505R Build/FRG83) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1");
InputStream is = null;
HttpGet httpGet = new HttpGet (address);
HttpResponse response = httpclient.execute(httpGet);
HttpEntity entity = response.getEntity();
is = entity.getContent();
InputStream is = null;
Try :
URLConnection cn= new URL(url).openConnection();
BufferedReader input = new BufferedReader( new InputStreamReader( cn.getInputStream() ) );
Read input stream.
Sounds like you're getting a mobile version of the site. If you extend the URL to include ?siteversion=pc you should get the page as served to a browser on your computer.
Try this:
StringBuilder builder = new StringBuilder();
String line = null;
HttpGet get = new HttpGet("http://www.url.com");
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(get);
InputStream is = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
while ((line = reader.readLine()) != null) builder.append(line);
Then, the page source should be in builder.
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