Convert an inputstream to a string value in Java Android App - java

I'm having trouble with function(s) I'm writing. I'm trying to convert an inputstream to a string value. I've written two functions and I'm attempting to extract the String value but my Log.e response is returning NULL. Below is my syntax. What am I doing wrong? Thanks
public JSONArray GetCityDetails(String StateID) {
#SuppressWarnings("deprecation")
String url = "http://mywebsite.com/getCity.php?StateID="+URLEncoder.encode(StateID);
HttpEntity httpEntity = null;
try{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
httpEntity = httpResponse.getEntity();
} catch(ClientProtocolException e){
e.printStackTrace();
} catch(IOException e){
e.printStackTrace();
}
JSONArray jsonArray = null;
if(httpEntity !=null){
try{
InputStream entityResponse = httpEntity.getContent();
// not working
String entityResponseAfterFunctionCall2 = readFully(entityResponse);
// not working
String entityResponseAfterFunctionCall3 = letsDoThisAgain(entityResponse);
Log.e("Entity Response Dude: ", entityResponseAfterFunctionCall3);
jsonArray = new JSONArray(entityResponseAfterFunctionCall3);
} catch(JSONException e){
e.printStackTrace();
} catch(IOException e){
e.printStackTrace();
}
}
return jsonArray;
}
public String readFully(InputStream entityResponse) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length = 0;
while ((length = entityResponse.read(buffer)) != -1) {
baos.write(buffer, 0, length);
}
return baos.toString();
}
public String letsDoThisAgain(InputStream entityResponse){
InputStreamReader is = new InputStreamReader(entityResponse);
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(is);
try {
String read = br.readLine();
while(read !=null){
sb.append(read);
read = br.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
}

if(inputStream != null)
{
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(inputStream));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
else
{
return "";
}

Your readFully call will use your system's default character encoding to transform byte buffer into String. This is NOT what you want to happen.
You should use explicit character set in toString call. The encoding is usually specified in the HTTP request header.
Here is an example of how to convert a UTF-8 encoded string
return baos.toString( "UTF-8" );
Your second problem, is once you've consumed the InputString in readFully call, the letsDoThisAgain will not have anything to read, because the InputStream will be at the EOF.

Related

My program won't pass through HttpPost

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.

HttpURLConnection GET request on Android gives weird 501 code

I have a weird issue when using HttpURLConnection on android it gives me a status code 501 but when I try the request on curl, it gives me status code 200.
curl -X GET \
-H "Accept-Charset: UTF-8" \
https://domain.com/v1/resource?token=token12345
This is my HttpURLConnection GET request snippet
public MyResponse get(String params) {
HttpURLConnection connection = null;
InputStreamReader inputStream = null;
BufferedReader reader = null;
MyResponse response = null;
String tokenParam = "?token=" + params;
try {
URL url = new URL(BASE_URL + API_VER + mResource + tokenParam);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(Method.GET);
connection.setRequestProperty(Header.ACCEPT_CHARSET, Value.UTF_8);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
int statusCode = connection.getResponseCode(); // code 501
inputStream = new InputStreamReader(connection.getInputStream());
reader = new BufferedReader(inputStream);
StringBuilder message = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
message.append(line);
}
response = new MyResponse();
response.setMessageBody(message.toString());
response.setStatusCode(statusCode);
if (statusCode == HTTP_OK || statusCode == HTTP_CREATED) {
response.setSuccess(true);
} else {
response.setSuccess(false);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) connection.disconnect();
try {
if (inputStream != null) inputStream.close();
if (reader != null) reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return response;
}
Am I missing anything?
setDoOutput(true) is used for POST and PUT requests for sending (output) a request body. Usually we don't need this for GET requests. Found it here
Ignore the timeout stuff if you don't need it.
The method at the bottom just takes an input stream and converts it into a response for you.
Hope it helps.
public boolean genLogon(){
HttpGet m_httpGet = null;
HttpResponse m_httpResponse = null;
// setup timeout params for the socket and the time to connect
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = CONNECTION_TIMEOUT;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = DATA_TIMEOUT;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
// Create a http client with the parameters
HttpClient m_httpClient = new DefaultHttpClient(httpParameters);
String result = null;
try {
// Create a get object
m_httpGet = new HttpGet("https://domain.com/v1/resource?token=token12345");
m_httpGet.setHeader(Accept-Charset, "UTF-8");
m_httpResponse = m_httpClient.execute(m_httpGet);
HttpEntity entity = m_httpResponse.getEntity();
if (entity != null) {
// Get the input stream and read it out into response
InputStream instream = entity.getContent();
result = convertStreamToString(instream);
// now you have the string representation of the HTML request
instream.close();
}
} catch (ConnectTimeoutException cte) {
// Toast.makeText(MainApplication.m_context, "Connection Timeout", Toast.LENGTH_SHORT).show();
return false;
} catch (Exception e) {
return false;
} finally {
m_httpClient.getConnectionManager().closeExpiredConnections();
}
// See if we have a response
if (m_httpResponse == null) {
return false;
}
// check status
if (m_httpResponse.getStatusLine() == null) {
return false;
}
// If the status code is okay (200)
if (m_httpResponse.getStatusLine().getStatusCode() == 200) {
//Handle the repsonse
return true
} else {
// response code not 200
}
return false;
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine() method. We iterate until the
* BufferedReader return null which means there's no more data to read. Each line will appended to a
* StringBuilder and returned as String.
*/
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();
}

how to post json objects to webservices like url

I want to pass JSON objects to web services like this
firstname=jhon&lastname=mic&mail=jhon#gmail.com&sex=M&hometown=blablabla
how can I pass,any one please help me.Am trying like this
JSONObject json = new JSONObject();
json.put("firstname", firstname);
json.put("lastname", laststname);
json.put("mail", mail);
json.put("sex", sex);
json.put("hometown", hometown)
HttpClient client=new DefaultHttpClient();
HttpPost post=new HttpPost(url);
post.setEntity(new ByteArrayEntity(json1.toString().getBytes("UTF8")));
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
if(entity!=null)
{
InputStream instream=entity.getContent();
String result=convertStreamToString(instream);
}
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();
}
But this code not posted the right value to webservice,Is there any wrong please help me ,
Thank you:)
StringBuilder bu = new StringBuilder();
for(int i = 0; i<json.names().length(); i++){
bu.append("&");
try {
bu.append(json.names().getString(i)+"="+json.get(json.names().getString(i)));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
bu.toString();//give you parameters

How to Decode String in Java or android?

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

How do I display a Java HttpPost object as a string?

I am creating an HttpPost object in Android to communicate with a server operated by a client. Unfortunately the server isn't providing either of us with very useful error messages; I would like to see the content of the HttpPost object as a string so I can send it to our client and he can compare it with what he's expecting.
How can I convert an HttpPost object into a string that reflects how it would look as it arrived at the server?
Should use it after execute
public static String httpPostToString(HttpPost httppost) {
StringBuilder sb = new StringBuilder();
sb.append("\nRequestLine:");
sb.append(httppost.getRequestLine().toString());
int i = 0;
for(Header header : httppost.getAllHeaders()){
if(i == 0){
sb.append("\nHeader:");
}
i++;
for(HeaderElement element : header.getElements()){
for(NameValuePair nvp :element.getParameters()){
sb.append(nvp.getName());
sb.append("=");
sb.append(nvp.getValue());
sb.append(";");
}
}
}
HttpEntity entity = httppost.getEntity();
String content = "";
if(entity != null){
try {
content = IOUtils.toString(entity.getContent());
} catch (Exception e) {
e.printStackTrace();
}
}
sb.append("\nContent:");
sb.append(content);
return sb.toString();
}
snippet
I usually do post in this way (The server answer is a JSON object) :
try {
postJSON.put("param1", param1);
postJSON.put("param2",param2);
} catch (JSONException e) {
e.printStackTrace();
}
String result = JSONGetHTTP.postData(url);
if (result != null) {
try {
JSONObject jObjec = new JSONObject(result);
}
} catch (JSONException e) {
Log.e(TAG, "Error setting data " + e.toString());
}
}
And postData is:
public static String postData(String url, JSONObject obj) {
// Create a new HttpClient and Post Header
HttpClient httpclient = null;
try {
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 30000);
HttpConnectionParams.setSoTimeout(myParams, 30000);
httpclient = new DefaultHttpClient(myParams);
} catch (Exception e) {
Log.e("POST_DATA", "error in httpConnection");
e.printStackTrace();
}
InputStream is = null;
try {
HttpPost httppost = new HttpPost(url.toString());
//Header here httppost.setHeader();
StringEntity se = new StringEntity(obj.toString());
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// // Do something with response...
is = entity.getContent();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// convert response to string
BufferedReader reader = null;
String result = null;
try {
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
} finally {
try {
if (reader != null)
reader.close();
if (is != null)
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (result != null) {
try {
#SuppressWarnings("unused")
JSONObject jObjec = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
return result;
}
Hope it helps
Well i actually did HTTP-Post using NameValuePair...... I am showing the code which i use to do an HTTP-Post and then converting the Response into a String
See the below Method code:
public String postData(String url, String xmlQuery) {
final String urlStr = url;
final String xmlStr = xmlQuery;
final StringBuilder sb = new StringBuilder();
Thread t1 = new Thread(new Runnable() {
public void run() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urlStr);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("xml", xmlStr));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
Log.d("Vivek", response.toString());
HttpEntity entity = response.getEntity();
InputStream i = entity.getContent();
Log.d("Vivek", i.toString());
InputStreamReader isr = new InputStreamReader(i);
BufferedReader br = new BufferedReader(isr);
String s = null;
while ((s = br.readLine()) != null) {
Log.d("YumZing", s);
sb.append(s);
}
Log.d("Check Now",sb+"");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t1.start();
try {
t1.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Getting from Post Data Method "+sb.toString());
return sb.toString();
}

Categories

Resources