Made an app to translate different words to different Language
Using Yandex converter getting proper results on Browser
converting Kiss
RESULTS as JSON object is
{"code":200,"lang":"en-hi","text":["चुम्बन"]} //proper
but while getting result on app
RESULT
{"code":200,"lang":"en-hi","text":["à¤à¥à¤®à¥à¤¬à¤¨"]}
JSONParser jParser = new JSONParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
geJSONFromUrl function
public JSONObject getJSONFromUrl(String urlSource) {
//make HTTP request
try {
URL url = new URL(urlSource);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
inputStream = new BufferedInputStream(urlConnection.getInputStream());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Read JSON data from inputStream
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
inputStream.close();
json = sb.toString();
} catch (Exception e) {
Log.e(TAG, "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e(TAG, "Error parsing data " + e.toString());
}
return jObj;// return JSON String
}
}
Is there any way i can get proper results?
Please HelpRegards
changed
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
to
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
Related
I need to post request to an API inside catch to store some logs.
But when I put it the request inside catch, it returned:
java.io.IOException: Server returned HTTP response code: 500 for URL
Code:
try {
...
} catch (Exception e) {
postRequest(...);
}
Code Post Request to API;
public static Object postRequest(...) throws IOException, ParseException {
URL url = new URL(API + "/" + pathName);
HttpURLConnection connection = getHttpURLConnection(url);
try (OutputStream os = connection.getOutputStream()) {
byte[] input = body.getBytes("utf-8");
os.write(input, 0, input.length);
}
try {
StringBuilder response = new StringBuilder();
InputStreamReader inputStreamReader = new InputStreamReader(connection.getInputStream(), "utf-8");
BufferedReader br = new BufferedReader(inputStreamReader);
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
JSONParser parser = new JSONParser();
JSONObject obj = (JSONObject) parser.parse(response.toString());
return obj;
} catch (IOException err) {
return null;
}
}
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.
In my android project I have a class for the HTTP requests to my server. There I have methods for sendGet, sendPost and sendPut. Here is the code for the sendPost method:
public JSONObject sendPost(String urlString, String urlParameters) {
URL url;
JSONObject jObj = null;
String json = "";
try{
url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
json = sb.toString();
} catch (MalformedURLException e){
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
try{
jObj = new JSONObject(json);
}
catch (JSONException e){
e.printStackTrace();
}
System.out.println(jObj);
return jObj;
}
It should return the server response as a JSONObject. If I send a post to my server, I get the following exceptions:
java.io.FileNotFoundException: http://... (In the line where I create the BufferedReader)
org.json.JSONException: End of input at character 0 of (In the line where I do jObj = new JSONObject(json);)
But if I copy the url to my browser there are no problems with it. And it seems like everything is working, because my server has received and processed the request. But why I get these errors and an empty JSONObject as result?
EDIT:
On my node.js server I send responses in the following format:
res.status(200).json({ success: "true" });
or
res.status(400).json({ success: "false", message:"..." });
EDIT 2:
After #greenapps comment I changed my code a bit:
...
json = sb.toString();
jObj = new JSONObject(json);
br.close();
wr.flush();
wr.close();
} catch (MalformedURLException e){
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
catch (JSONException e){
e.printStackTrace();
}
return jObj;
Now the JSONException is gone, but the FileNotFoundException is still there and the jObj is still empty when it got returned.
I had a bug in my node.js server and the response code of the server was 502. And the BufferedReader only works with a 200 status code. Thats why I got the exceptions. Now I have a if around the BufferedReader:
if(connection.getResponseCode() == 200) {
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
json = sb.toString();
jObj = new JSONObject(json);
br.close();
}else{
json = "{ success: \"false\" }";
jObj = new JSONObject(json);
}
I new to android and want to call web service written in PHP from android application; but I am getting InputStream as null. But when I tried to run same URL from browser it is showing the output.
My php file: (userlogin.php)
<?php
$con=mysqli_connect("IP Address of server","Any","","user");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username = $_GET['username'];
$password = $_GET['password'];
$result = mysqli_query($con,"SELECT * FROM userLogin where username = '$username' and password = '$password'");
$n_filas = mysqli_num_rows ($result);
$array = array();
for ($i=0; $i<$n_filas; $i++)
{
$fila = mysqli_fetch_array($result);
$array[$i]['username'] = utf8_encode($fila['username']);
$array[$i]['password'] = utf8_encode($fila['password']);
}
$result= json_encode($array);
echo $result;
mysqli_close($con);
?>
and my JSON parser :
public JSONArray makeHttpRequest(String url, ArrayList<String> params) {
try
{
URL url1 = new URL("http://IP ADDRESS OF SERVER/userlogin.php?username="+params.get(0)+"&password="+params.get(1));
urlConnection = (HttpURLConnection) url1.openConnection();
urlConnection.connect();
is = urlConnection.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
Log.d("String is",is.toString());
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.d("String ===",json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try
{
Log.d("In JSON Object try ", "yes");
jObj = new JSONArray(json);
Log.d("String Json ===",jObj.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
Any help will be appreciated. Thank You.
The following works for me:
public static void retrieveData() {
try {
// the following line is BAD - do not supply username + password via such an insecure connection!
URL url1 = new URL("http://IP ADDRESS OF SERVER/userlogin.php?username="+params.get(0)+"&password="+params.get(1));
URLConnection urlConnection = url1.openConnection();
// you may want to adjust the timeout here, like so:
// urlConnection.setConnectTimeout(timeout);
urlConnection.connect();
try (InputStream is = urlConnection.getInputStream()) {
processData(is);
} catch (IOException e) {
// do something smart
}
} catch (MalformedURLException e) {
// do something smart
} catch (IOException e) {
// do something smart
}
}
private static void processData(InputStream is) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
// rest of your processing logic
} catch (IOException e) {
// do something smart
}
}
These methods do not necessarily have to be static and you may of course amend their signature (parameters, return value) to suit your needs.
I know that this has been asked but most are out dated, and method are deprecated. I have found this solution,
new Thread( new Runnable() {
#Override
public void run() {
try {
String query = "param=" +"item"+"&other="+"num";
URL url = new URL("http://www.url.com/url_post.php");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
//Set to POST
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setReadTimeout(10000);
Writer writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(query);
writer.flush();
writer.close();
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e(TAG, e.toString());
}
}
}).start();
But, it does not provide how to get data that is returned for example, I am return some JSON, where get I get that data that is returned?
Thanks for the help :)
Do this
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
Finally in response you will get response JSON string then do what you want to do.
For more details visit this link
http://www.xyzws.com/javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139
I recommend you to use this project as library:
https://github.com/matessoftwaresolutions/AndroidHttpRestService
It's extremely easy and I use it for all my projects. I commited it to Github because it is difficult for me to find an easy Rest client for general purpose.
I'm going to commit an update for integration with Android Studio ASAP.
I hope it helps!!
InputStream in = connection.getInputStream();
JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
Add this part after your writer.close()
connection.connect();
int statusCode = connection.getResponseCode();
Log.d("ON POST", " The status code is " + statusCode);
if (statusCode == 200) {
is = new BufferedInputStream(connection.getInputStream());
String response = convertInputStreamToString(is);
Log.d("ON POST", "The response is " + response);
return response;
} else {
Log.d("ON POST", "On Else");
return "";
}
The ConvertInputStreamToString() should be created to return your json as string
public static String convertInputStreamToString(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}