HttpClient wont work in jelly bean? - java

I've build app android uses http client to get content from URL,
String getRequest(String SUrl){
String vResult = "TEST";
//SUrl result of "http://mydomain.com/file.php?var=21"
HttpClient client = new DefaultHttpClient();
HttpGet request;
try{
request=new HttpGet(SUrl);
HttpResponse response = client.execute(request);
vResult=request(response);
}catch(Exception ex){
Log.e("From Server", ex.getMessage());
}
return vResult;
}
public static String request(HttpResponse response){
String result = "";
try{
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
str.append(line + "\n");
}
in.close();
result = str.toString();
}catch(Exception ex){
result = "Error";
}
return result;
}
in android gingerbread the code above work fine get content from server,but in jelly bean the code result log like this
java.lang.NullPointerException: println needs a message
why i get null in jelly bean even i already declare all variable?
thanks

Try this..
catch(Exception ex){
Log.e("From Server", ""+ex.printStackTrace());
}

Related

Force java.net.HttpUrlConnection to return GET-response regardless of Http-Status-Code

I'm working on a HTTP-Client to sent GET-Requests to an API, which responds with proper JSON-Objects even when the HTTP-Status Codes contains an Error such as 401.
public String get(String url){
URL target;
HttpURLConnection connection;
int code = 200;
BufferedReader reader;
String inputLine;
String result = null;
try {
target = new URL(url);
} catch (MalformedURLException ex) {
return result;
}
try {
connection = (HttpURLConnection)target.openConnection();
connection.setRequestMethod("GET");
connection.connect();
//code = connection.getResponseCode();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
result = "";
while ((inputLine = reader.readLine()) != null){
result += inputLine;
}
reader.close();
} catch (IOException ex) {
return "...";
}
return result;
}
When that's the case, the IOException is thrown and the response isn't written. However, I want to receive the response regardless of the HTTP-Status-Code and hande error handling myself. How can I achieve this?
I don't believe you can do that, but there's https://docs.oracle.com/javase/8/docs/api/java/net/HttpURLConnection.html#getErrorStream-- for getting the payload in case of an error.

Send HTTP Post with querystring in URL

I have doubts about send HTTP Post using querystring.
I have the follow code below but thie code not working. I try send by web service the user and password, embedded in URL, but it not working. this code cannot connect on web-service.
#Override
protected String doInBackground(String... params) {
String result = "";
try {
URL url = new URL("http://192.168.0.11:8080/api/Usuario/doLogin?user="+user+"&senha="+password);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = bufferedReader.readLine()) != null) {
response.append(inputLine);
}
result = response.toString();
bufferedReader.close();
} catch (Exception e) {
Log.d("InputStream", e.getMessage());
}
return result;
}
I think you mean GET request not POST,
and you should encode the variables in the query params, "user" and "password" in your case.
URL url = new URL("http://192.168.0.11:8080/api/Usuario/doLogin?user=" + URLEncoder.encode(user, "UTF-8")+"&senha="+ URLEncoder.encode(password, "UTF-8"));

How to get text from website to string?

How to get XML from this URL into String on Android? I was trying to do it with tutorials, but no way was successful. Here is my code:
public String getXmlFromUrl(String url) {
String text = "";
try {
HttpGet get = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(get);
InputStream inputStream = response.getEntity().getContent();
String line = "";
BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
while ((line = rd.readLine()) != null) {
text += line;
}
} catch (Exception e) {
e.printStackTrace();
}
return text;
}

Creating a thread in android not working

I have a method that I'm calling but, for newer versions of Android it fails. Apparently, this is due to the lack of threading. My method is to send a message to my server. This is the code (sans threading)
public String sendMessage(String username, Editable message){
BufferedReader in = null;
String data = null;
try{
DefaultHttpClient client = new DefaultHttpClient();
URI website = new URI("http://abc.com/user_send.php?username="+username+"&message="+message);
HttpPost post_request = new HttpPost();
post_request.setURI(website);
HttpGet request = new HttpGet();
request.setURI(website);
//executing actual request
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.separator");
while ((l = in.readLine()) != null) {
sb.append(l);
}
in.close();
data = sb.toString();
return data;
}catch (Exception e){
return "ERROR";
}
}
Now, just trying to put a thread around it:
public String sendMessage(String username, Editable message){
BufferedReader in = null;
String data = null;
Thread sendThread = new Thread(){
try{
DefaultHttpClient client = new DefaultHttpClient();
URI website = new URI("http://thenjtechguy.com/njit/gds/user_send.php?username="+username+"&message="+message);
HttpPost post_request = new HttpPost();
post_request.setURI(website);
HttpGet request = new HttpGet();
request.setURI(website);
//executing actual request
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.separator");
while ((l = in.readLine()) != null) {
sb.append(l);
}
in.close();
data = sb.toString();
return data;
}catch (Exception e){
return "ERROR";
}
} sendThread.start();
}
But that doesn't work. What am I doing wrong? Also, if you notice I'm breaking any fundamental rules in android regarding the HttpClient, please let me know.
Your implementation is not correct - you did not override run() method
class SendThread extends Thread {
public void run(){
//add your implementation here
}
}
Tow start the thread
SendThread sendThread = new SendThread();
sendThread.start();
Better to a head and use AsyncTask concept.
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
Refer this LINK for sample implementation

Reading line from website

I am making a little program thath will read data from website. String in the html file is already managed every info is divided with ; . Now i should read complete line here is example of this line:
14:47;24.02.12;18.7°C;18.7°C;285;0.5m/s; 6:48;17:37; Warm ;36;1.8;0.0;
So first how should i read them with HTTP Get or is there anything other? And then i would like to save each info, they are seperated with ; into a variable. And how should i cut each info from this line.
You definitely need to do some homework, but this methods will help you:
public static String getContentFromUrl(String url) throws ClientProtocolException, IOException {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response;
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inStream = entity.getContent();
String result = HttpService.convertStreamToString(inStream);
inStream.close();
return result;
}
return null;
}
private 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();
}
This allows you to get data from a URL. Then lookup String.split to chop your string into usable entities.
Hope this helps!
Use GET request to fetch the data from the website
Separate the string-data from the HTML-markup
Parse the string into multiple strings or a list of strings, using ';' as the delimiter.
Android Java SDK String reference

Categories