Java, HttpClient issue (android) - java

Past few hours I have been working on this without any luck.
public void OnClickEventOnButton(View view)
{
this.commonContext = new BasicHttpContext(); //defined in the class to acihive
HttpClient httpClient=new DefaultHttpClient();
HttpGet get=new HttpGet("http://somesite.com");
HttpResponse response=null;
try{
response=httpClient.execute(get);
if(response.getStatusLine().getStatusCode()==200)
{
}
}catch(ClientProtocolException e){
alert(e.toString(),"エラ");
}
catch (IOException e) {
alert("HTTPHelp : IOException : "+e,"エラ");
}
catch(NullPointerException e){
alert("Null pointer : "+e.getCause(), "sfasfd");
}
}
The line below where my exception is generating
response=httpClient.execute(get);
The error my device showing is Unfortunately, Data Retriver has stopped.
If you need any more information, please let me know. If you need any specific data, please guide me, just started learning, I will provide the data.

Just a guess, but do you
a) don't have the INTERNET permission added in your manifest?
- this means you should see a "IllegalStateException" in your logcat
b) you execute Network on the applications main thread?
- this means you should see a "NetworkOnMainthreadException in your logcat

Related

Can't fetch expanded URL from a given shortened URL

I am given a shortened url and I want to get the expanded form. The below java function is used to achieve this.
public String expand(String shortenedUrl){
URL url = null;
try {
url = new URL(shortenedUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
// open connection
HttpURLConnection httpURLConnection = null;
try {
httpURLConnection = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
} catch (IOException e) {
e.printStackTrace();
}
// stop following browser redirect
httpURLConnection.setInstanceFollowRedirects(false);
// extract location header containing the actual destination URL
String expandedURL = httpURLConnection.getHeaderField("Location");
httpURLConnection.disconnect();
return expandedURL;
}
The code works fine in Eclipse but the same doesn't work in android.
String expandedURL = httpURLConnection.getHeaderField("Location");
The above line throws java.lang.RuntimeException: Unable to start activity ComponentInfo. And the error is pointed to the above line. If I remove the above line no error is encountered. Even I am not able to use getResponseCode() function.
int status = 0;
try {
status = httpURLConnection.getResponseCode();
} catch (IOException e) {
e.printStackTrace();
}
This piece of code also has the same problem. works in eclipse but not in android.
Any kind of help will be greatly appreciated.
Edit: The code using above function is,
ExpandUrl expandUrl = new ExpandUrl();
String expandedUrl = expandUrl.expand(shortenedUrl);
Note: The function expand is defined inside the class ExpandUrl.
Well, the code works in Eclipse but not in android. The reason is that you are doing it in Main thread and blocking it. Android wouldn't allow you to do so and throw runtime error.
I have tried to implement your code using AsyncTask in android. It works fine.
Give it a try.
To know more about AsyncTask follow: Android Documentation on AsyncTask
Good Luck!

Android URLEncoder.encode unhandled exception java.io.UnsupportedEncodingException

I try to implement Android searchable and I want to filter query, I follow this link, this, and others. but in Android Studio I got this message unhandled exception java.io.UnsupportedEncodingException, this is my code
import java.net.URLEncoder;`
private void doSearch(String queryStr) {
// get a Cursor, prepare the ListAdapter
// and set it
//Log.e("Query",queryStr);
searchRestaurants(URLEncoder.encode(queryStr, "UTF-8"));}
You need to wrap your URLEncoder.encode()-method in a try-catch block:
try {
URLEncoder.encode(queryStr, "UTF-8");
} catch (UnsupportedEncodingException e) {
Log.e("Yourapp", "UnsupportedEncodingException");
}
The reason you're getting this error is that some platforms might not support UTF-8 encoding. Android definitely does, so you'll never receive this Exception, but you still need to handle it to make the compiler happy.
However, your code won't do anything, you'll need to store the result of the encode()-operation in a variable, e.g. String myEncodedQuery = URLEncoder.encode(queryStr, "UTF-8");.
import java.net.URLEncoder;
private void doSearch(String queryStr) {
// get a Cursor, prepare the ListAdapter
// and set it
//Log.e("Query",queryStr);
try {
final String encodedPath = URLEncoder.encode(queryStr, "UTF-8"));
searchRestaurants(encodedPath);
} catch (UnsupportedEncodingException ec) {
Log.d(TAG, ec.printStacktrace);
}
}

javax.net.ssl.SSLHandshakeException: Connection reset by peer

I use following code to call an Azure mobile backend API in my Android app,
try {
mobileClient.invokeApi("CustomTransaction", senderToCheck,
Boolean.class, new ApiOperationCallback<Boolean>() {
#Override
public void onCompleted(Boolean result,
Exception error, ServiceFilterResponse response) {
if (error == null) {
CheckSender(result);
} else {
dial.dismiss();
Crouton.makeText(MyActivity.this,
"Eror Occured with service",
Style.ALERT).show();
}
}
});
} catch (SecurityException e) {
Log.d(TAG, "CouldNotConnectToSocket", e);
e.printStackTrace();
} catch (IllegalArgumentException e) {
Log.d(TAG, "CouldNotConnectToSocket", e);
e.printStackTrace();
}
Other information:
CustomTransaction - API Controller name;
senderToCheck - JSON parsable data transfer object;
Boolean.class - return type; and 4th parameter is the callback method
All objects are JSON parsable and this worked like several days ago.
So this API call/Azure call always times out giving a What does "connection reset by peer" mean? ,SSLHandShakeExceptionand and most of the time Connect gets Timed out.
Main cause for the problem is com.microsoft.windowsazure.mobileservices.MobileServiceException: Error while processing request.
I tried re-publishing my asp.net web app several times but it never hits controller action where my debugger point is placed when debugging the service call remotely.
I checked if my service is down, found it is up & running then checked Azure management portal logs, found out traceApi messages of some controller action methods. and of SQL Cpu usages and Data out packet sizes., but I never gets a proper reply from anywhere to solve this problem for two weeks now.
In case,if I am correct, think the solution for this problem lies in http://www.webapper.com/blog/index.php/2007/02/09/troubleshooting-javaxnetsslsslhandshakeexception/ but Im not pretty sure on doing it.
Please advise me on getting this fixed

Apache's HttpClient falls asleep in Swing application

I faced very strange problem. Writing an application to download some data from Internet with proxy server support I decided to use Apache's HttpClient library. jar binaries were successfully added to NetBeans project and the following code snippet was executed (successfully too) in a simple application:
DefaultHttpClient httpclient = new DefaultHttpClient();
String proxyHost = "192.168.4.10";
Integer proxyPort = 8080;
HttpHost targetHost = new HttpHost("noaasis.noaa.gov", 80, "http");
HttpGet httpget = new HttpGet("/ptbus/ptbus167");
try {
HttpHost proxy = new HttpHost(proxyHost, proxyPort);
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
System.out.println("executing request: " + httpget.getRequestLine());
System.out.println("via proxy: " + proxy);
System.out.println("to target: " + targetHost);
HttpResponse response = httpclient.execute(targetHost, httpget);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
Header[] headers = response.getAllHeaders();
for (int i = 0; i<headers.length; i++) {
System.out.println(headers[i]);
}
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
EntityUtils.consume(entity);
}
catch (IOException ex) {
}
finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
But when I try to do the same thing in Swing application it doesn't work. For example, rewriting default Netbeans desktop application's "about" action listener as follows
#Action
public void showAboutBox() {
new Thread(new Runnable() {
public void run() {
DefaultHttpClient httpclient = new DefaultHttpClient();
......
......
......
finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}).start();
}
causes application's execution to stop somewhere in
HttpResponse response = httpclient.execute(targetHost, httpget);
Leastways, it never returns...
The interesting thing is if I also put this code snippet in application's main method just before creating any Swing instance the mentioned line is passed and HTTP response is received. And calling showAboutBox() doesn't cause the problem anymore then - I receive HTTP response too.
What am I doing wrong, guys? What's the trick? Can I use Apache's library in my Swing application? I cannot understand what happens and didn't find anything similar to this spending hours in the net.
Thank You for attention. Hope for any help!
You're blocking the event dispatch thread (EDT). Use SwingWorker, as shown here.
that only comments but its longer than allowed number of chars....
to avoid wrong directions, Swing based gui doesn't any care that you running any of BackGround Task, Swing is single threaded and all output to the GUI must be done on EDT
1/ wrap output to the GUI to the SwingUtilities.invokeLater(), that's created your own EDT, and if there EDT exist then move actual task to the ends of the EDT
2/ wrap output to the GUI by using javax.swing.Action
3/ or as trashgod suggested let's SwingWorker works for that +1
I solved the problem by excluding org.jdesktop.application.SingleFrameApplication and replacing FrameView by JFrame. Of course, one loses advantages of FrameView but all required things can be implemented extending JFrame.
Unfortunately, I have no enough time to examine why HttpClient doesn't work with SingleFrameApplication so the solution proposed is acceptable for me.
Hope this will help somebody else.
And thanks to trashgod and mKorbel for participation. Thank you, guys. Both +1.

Android TCP - program crashes

I cant seem to get a simple TCP connection going between a java server application and Android (I have tried both the emulator and the Android Dev Phone 2). I am getting this error on the Emulator "The application Data Receive (process com.mdog.datareceive) has stopped unexpectedly. Please try again."
Forgive me but I am very new to android. So I don't know how to debug it... but I am not trying anything too complex. Eventually I want to try and "consume" the bytes I am receiving in the application. and have the TCP run in the background... but for now simply getting the phone and computer to communicate would be great.
If you can help me that would be awesome.
Code for Android side:
public class Receive extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = new TextView(this);
Socket connectionSocket = null;
byte[] inputHolderByteArray = new byte[5*1024];
/* Connect to Server */
try {
connectionSocket = new Socket("192.168.0.104", 11313);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
/* Send an s to server to start transmission */
try {
PrintWriter out = new PrintWriter(connectionSocket.getOutputStream(), true);
out.print('s');
out.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
/* read server transmission */
try {
connectionSocket.getInputStream().read(inputHolderByteArray);
} catch (IOException e) {
e.printStackTrace();
}
tv.setText("done");
setContentView(tv);
}
}
Each instance of the emulator runs behind a virtual router/firewall service that isolates it from your development machine's network interfaces and settings and from the internet.
The virtual router for each instance manages the 10.0.2/24 network address space — all addresses managed by the router are in the form of 10.0.2., where is a number. Addresses within this space are pre-allocated by the emulator/router.
You have to refer to the development machine with address as: 10.0.2.2 instead of 192.168.0.104 in your case. If you want to refer to another machine in your LAN, then you can Use Network Redirections
http://developer.android.com/guide/developing/tools/emulator.html#emulatornetworking
While superfell is correct that the full stack trace would help diagnose this, based on your code the/a likely problem is that you are breaking up every statement into it separate try/catch blocks. This probably isn't your core issue(my guess is you have a networking issue), but it is what is causing the system to crash.
Typically in Java, statements that are reliant on each other which can throw Exceptions are put in the same try/catch statement. What is most likely happening for you is that the code enters your first try catch block where you try to define a new socket. This fails throwing an exception like 'UnknownHostException'. connectionSocket remains null but the code enters the catch for UnknownHostException. You print the stack trace, but the program doesn't exit. Your code continues on to the following try/catch block where you call
PrintWriter out = new PrintWriter(connectionSocket.getOutputStream(), true);
This causes a NullPointerException. This is a RuntimeException which is not checked and, because it is unchecked, you are not forced to catch it in a catch statement. The exception now causes your VM to crash and causes the error screen you have reported.
So, even though getting the logcat stacktrace will tell us more about your issue, the code you have constructed should be condensed into a single try/catch statement since all code is dependent on the first try/catch completing without error.
Edit:
Try constructing your application like this
public class Receive extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = new TextView(this);
Socket connectionSocket = null;
byte[] inputHolderByteArray = new byte[5*1024];
/* Connect to Server */
try {
connectionSocket = new Socket("192.168.0.104", 11313);
PrintWriter out = new PrintWriter(connectionSocket.getOutputStream(), true);
out.print('s');
out.flush();
connectionSocket.getInputStream().read(inputHolderByteArray);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
tv.setText("done");
setContentView(tv);
}
}
When we say 'get the stacktrace', this means you need to connect to the emulator or device using the android debug bridge (adb) and a program called logcat. If you only have the emulator and no phone connected to your pc, try running the following:
adb logcat *:D
This will output the log information to the terminal. Leave this window open and run your application. You should see a stack trace get printed. Please take the time to get to know logcat and adb.

Categories

Resources