I get Data from Json in android,date get and save in String Variable.but when use DecodeUrl its error:
Error: java.lang.IllegalArgumentException: Invalid % sequence at 40:
my code:
#SuppressLint("NewApi")
public String JsonReguest(String url) {
String json = "";
String result = "";
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
httpget.setHeader("Accept", "application/json");
httpget.setHeader("Content-Type", "application/json");
HttpResponse response;
try {
response = httpclient.execute(httpget);
response.setHeader("Content-Type","UTF-8");
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
result = convertStreamToString(instream);
InputStream stream = new ByteArrayInputStream(result.getBytes("UTF-8"));
result = convertStreamToString(stream);
// String encode_url=URLEncoder.encode(result,"UTF-8");
// String decode_url=URLDecoder.decode(encode_url,"UTF-8");
//result=decode_url;
//String decodedUrl = URLDecoder.decode(result, "UTF-8");
result=URLDecoder.decode(result);
}
} catch (Exception e) {
Log.e("Error", e.toString());
}
return result;
}
public static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
simple text of json :
{"CategoryID":11,"ParentID":0,"Title":"%u062E%u0648%u062F%u0631%u0648","PicAddress":""},{"CategoryID":16,"ParentID":0,"Title":"%u0627%u0645%u0644%u0627%u0643%20","PicAddress":""}
this line crashed : result=URLDecoder.decode(result);
how to Resolve Problems.
first decode specifing your encoding
String result = URLDecoder.decode(url, "UTF-8");
and then go to http://json.org/, scroll down and choose one of the supported json parsing Java libraries
As Selvin commented %uxxxx is not a standard Url encoded string , so it's obvious to get an error
you have 2 options:
Contact the service provider to fix her url encoded strings and use URLDecoder.decode in your code
write a custom decoder for such strings
P.S. ask your questions more clear to avoid getting negative points
Related
In my CountryActivity.java I have a HttpRequest to retrieve json information of the wikipedia.
This is the code I use AsyncTask:
private class DownloadFilesTask extends AsyncTask<URL, Integer, String> {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=Portugal");
protected String 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(Integer.parseInt("Downloaded "));
}
}
And, to call the class in my activity I use new DownloadFilesTask();.
The problem is, when I debug my private class, the debugger stops in the line HttpPost httpPost = new HttpPost("https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=Portugal"); and it can't even retrieve the json. Do you know what may be happening? My app doesn't crash or nothing...
This is my logcat: https://pastebin.com/EgVrjfVx
Open connection to url with HttpURLConnection and set setRequestMethod() to GET
URL obj = new URL("https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=Portugal");
HttpURLConnection http = (HttpURLConnection) obj.openConnection();
http.setRequestMethod("GET");
then gets its input stream and read via BufferedReader to your build.
BufferedReader reader = new BufferedReader(new InputStreamReader(http.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
reader.close();
String json_string = sb.toString(); // your json data
Check here full example to understand batter.
public static String[] Webcall(String emailID) {
try {
URL url = new URL(AppConfig.URL + emailID);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Authorization", "application/json");
conn.setRequestProperty("userEmailId", emailID);
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
org.json.JSONObject _jsonObject = new org.json.JSONObject(output);
org.json.JSONArray _jArray = _jsonObject.getJSONArray("manager");
String[] str = new String[_jArray.length()];
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
This is my code I am trying to call web service and get data.
But when I hit web service then I am getting below exception
Failed : HTTP error code : 404
Please suggest me where am doing wrong try to give solution for this .
The first thing is check url is it working on computer using postman or restclient and if it is working fine then tried to post using below code, this code is for posting data in json format using HttpPost you can use retrofit lib as Milad suggested.
public static String POST(String url, String email)
{
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("email", email);
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
I think u should try to re-check URL that you send request to.
follow the output error, code 404 that mean the URL is broken or dead link.
You can do the same by using jersy-client and jersy core.Here is the code snippet
private static void generateXML(String xmlName, String requestXML, String url)
{
try
{
Client client = Client.create();
WebResource webResource = client
.resource(url);
ClientResponse response = (ClientResponse)webResource.accept(new String[] { "application/xml" }).post(ClientResponse.class, requestXML);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}
String output = (String)response.getEntity(String.class);
PrintWriter writer = new PrintWriter(xmlName, "UTF-8");
writer.println(output);
writer.close();
}
catch (Exception e) {
try {
throw new CustomException("Rest-Client May Be Not Working From Your System");
} catch (CustomException e1) {
System.exit(1);
}
}
}
Call this method from your code with varibales.
What I'm trying to do is to generate a byte array from a url.
byte[] data = WebServiceClient.download(url);
The url returns json
public static byte[] download(String url) {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
try {
HttpResponse response = client.execute(get);
StatusLine status = response.getStatusLine();
int code = status.getStatusCode();
switch (code) {
case 200:
StringBuffer sb = new StringBuffer();
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
is.close();
sContent = sb.toString();
break;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sContent.getBytes();
}
This data is used as a parameter for String
String json = new String(data, "UTF-8");
JSONObject obj = new JSONObject(json);
for some reason, I get this error
I/global ( 631): Default buffer size used in BufferedReader constructor. It would be better to be explicit if an 8k-char buffer is required.
I think something there must be missing here sContent = sb.toString(); or here return sContent.getBytes(); but I'm not sure though.
1. Consider using Apache commons-io to read the bytes from InputStream
InputStream is = entity.getContent();
try {
return IOUtils.toByteArray(is);
}finally{
is.close();
}
Currently you're unnecessarily converting the bytes to characters and back.
2. Avoid using String.getBytes() without passing the charset as a parameter. Instead use
String s = ...;
s.getBytes("utf-8")
As a whole I'd rewrite you're method like this:
public static byte[] download(String url) throws IOException {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse response = client.execute(get);
StatusLine status = response.getStatusLine();
int code = status.getStatusCode();
if(code != 200) {
throw new IOException(code+" response received.");
}
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
try {
return IOUtils.toByteArray(is);
}finally{
IOUtils.closeQuietly(is.close());
}
}
I am trying to read the buffer (android application) and set the value to my TextView 'httpStuff'. But i dont think i am getting some response from the URI.
I don't get any runtime errors. I tried many flavour of the same logic. Nothing seems to be working.
INTERNET permission is already set in the manifest. SdkVersion="15". Any help ?
HttpClient client = new DefaultHttpClient();
URI website = new URI("http://www.mybringback.com");
HttpGet request = new HttpGet();
request.setURI(website);
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(is));
httpStuf.setText( in.readLine());
I think you are missing the while loop and also, when you say only in.readLine(), may be it is returning you an empty line from the response, though it is having enough data.So make sure to read the reader entirely like this and check its contents.
while ((line = rd.readLine()) != null) {
httpStuf.setText(line+"\r\n");
}
Hope this will help you.
This code worked for me
InputStream is = response.getEntity().getContent();
String strResponse = inputStreamToString(is);
private String inputStreamToString(InputStream is)
{
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is), 1024 * 4);
// Read response until the end
try
{
while ((line = rd.readLine()) != null)
{
total.append(line);
}
} catch (IOException e)
{
Log.e(TAG, "error build string" + e.getMessage());
}
// Return full string
return total.toString();
}
try to get the status code of response and Then you can compare with the (HTTP status)
int responseCode=response.getStatusLine().getStatusCode()
I am using this method to simply catch the HTTP response and it works fine for me.
public String httpGetResponse(String url) {
try {
Log.i("HTTP Request", "httpGet Request for : " + url);
DefaultHttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
//get.setHeader("Connection", "keep-alive");
HttpResponse response = client.execute(get);
InputStream is = response.getEntity().getContent();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(is));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
str.append(line + "\n");
}
return str.toString();
} catch (Exception e) {
Log.e("HTTP error", "Error in function httpGetResponse : "
+ e.getMessage());
return null;
}
}
I try to get HTML content, everything works find except 1 thing. It doesn't download whole code and skip the content which I want to extract(urls to images, names) and I have just blank classes 'obrazek'.
Here is the code i use to get source code:
String SourceCode(String adres) throws IllegalStateException, IOException
{
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(adres);
HttpResponse response = null;
try {
response = httpClient.execute(httpGet, localContext);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader reader = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()
)
);
String result = "";
while(reader.readLine() != null)
{
result += reader.readLine();
}
reader.close();
return result;
Thank you for help:)
You skip one line each time. should be
StringBuilder result = new StringBuilder();
String line;
while((line = reader.readLine()) != null)
{
result.append(line);
}
reader.close();
return result.toString();
BTW - I used StringBuilder to avoid creation of new String object each iteration - very recommended.