I'm getting an IOException from my code using AndroidHttpClient. Is there something wrong with the code? The code is thrown whether I use port 80 or port 443, and with Http Schema http or https.
The exception is thrown at client.execute...it is a UnknownHostException exception..I'm not sure why. I can hit the service from the browser.
// declare locals
JSONObject joResponse = new JSONObject();
String response = "";
try
{
// prepare to execute
HttpHost target = new HttpHost(hostname, Const.HTTP_PORT, Const.HTTP_SCHEME);
HttpGet get = new HttpGet();
ResponseHandler<String> responseHandler = new BasicResponseHandler();
AndroidHttpClient client = AndroidHttpClient.newInstance(null);
// execute
response = client.execute(target, get, responseHandler); // this is where the exception is thrown
joResponse = new JSONObject(response);
}
catch (ClientProtocolException e)
{
}
catch (IOException e)
{
}
catch(Exception e)
{
}
Do you have the internet permission declared in your app?
You need to add the following line to your AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
Related
I wrote a little programm, that reads an XML-File via http-get.
Loacally it's running fine.
But on the server it keeps breaking without any exception, except a nullpointer because of the empty result
I'm using the apache http lib.
Here is the class, i added the numbers, to track the exact point, where it stops working.
public void get(String url, String user, String pass, File outfile) throws IOException
{
log.info("1");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, "basic"),
new UsernamePasswordCredentials(user, pass));
log.info("2");
CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
HttpResponse response = null;
log.info("6");
InputStream content = null;
FileOutputStream outputStream = null;
try
{
HttpGet httpGet = new HttpGet(url);
log.info("3");
httpGet.addHeader("Content-Type", "text/xml");
log.info("4");
httpGet.addHeader("Accept", "text/xml");
log.info("5");
log.info("6");
log.info("7");
outputStream = new FileOutputStream(outfile);
log.info("8");
response = httpClient.execute(httpGet);
log.info("9");
log.info("response: {}", response);
log.info("10");
content = response.getEntity().getContent();
log.info("11");
log.info("content: {}", content);
log.info("12");
IOUtils.copy(content, outputStream);
log.info("13");
}
catch (Exception e)
{
log.error("", e);
}
finally
{
try
{
log.info("14");
log.info(String.valueOf(content));
content.close();
outputStream.close();
}
catch (IOException e)
{
log.error("Error while closing Streams", e);
}
}
}
Here are the log snipets; I tried to mask every sensible data and i hope i didn't miss anything
Local log snipet
Remote log snipet
As you can see, the numbers stop after 8 and start in the finally block again with 14. the rest is missing and I have no idea, why.
The used URL is reachable via browser or comandline.
The problem is a bit tricky: you are running into some sort of Error here. Probably NoClassDefFoundError or something alike.
But as you are catching for Exception this piece of code simply doesn't "see" the real problem.
So to debug the problem: either check the server log files or change your code to catch Throwable instead of Exception.
I am getting an error with the following line of code
HttpClient Client= new HttpClient, event I have add httpclient-4.2.3.jar to my project.
I have tried rewriting it as HttpClient Client= new DefaultHttpClient. But it solves the problem and creates a new error with other methods (in executeMethod()).
This is my code :
public static String POSTUpload(String url, String foto){
InputStream inputStream=null;
String result="";
HttpClient httpClient = new HttpClient();
PostMethod method = new PostMethod(url);
//set JSON ke hhtp post entity
// File file_foto= new File(foto);
// FileEntity fe_foto=new FileEntity(file_foto, "image/jpeg");
method.setRequestEntity(new FileRequestEntity(new File(foto), "multipart/form-data"));
// se.setContentType("application/json;charset=UTF-8");
// httpPost.setHeader("Accept", "application/json");
try {
int status = httpClient.executeMethod(method);
System.out.println("HTTP status " + method.getStatusCode()
+ " creating con\n\n");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace(); // TODO Auto-generated catch block
}finally {
method.releaseConnection();
}
}
is there anyone know why this is happen? Please Help
I'm trying to create new user to OpenStack using the api given in this link
http://docs.openstack.org/api/openstack-identity-service/2.0/content/POST_addUser_v2.0_users_Admin_API_Service_Developer_Operations-d1e1356.html
I have passed the token replied by the server when I logged-in.
This is my code for creating new user:
Log.i("TAG","Adding new User");
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.1.122:35357/v2.0/users");
try {
JSONObject newuser = new JSONObject();
JSONObject userInfo = new JSONObject();
newuser.put("user", userInfo);
//end of JsonArray
userInfo.put("username", "Lou Mary");
userInfo.put("email", "lagojo#owtel.com");
userInfo.put("enabled", true);
userInfo.put("OS-KSADM:password", "secret101");
Log.i("TAG", "passing your data"+newuser.toString());
// erequest.setText(auth.toString());
StringEntity params1 = new StringEntity(newuser.toJSONString());
params1.setContentEncoding("UTF-8");
//params1.setContentType("application/json");
Log.i("TAG","params" +params1);
httppost.setHeader("Content-type", "application/json");
httppost.setHeader("X-Auth-Token", "MIICbgYJKoZIhvcNAQcCoIICXzCCAlsCAQExCTAHBgUrDgMCGjCCAUcGCSqGSIb3DQEHAaCCATgEggE0eyJhY2Nlc3MiOiB7InRva2VuIjogeyJpc3N1ZWRfYXQiOiAiMjAxMy0xMS0yMlQwMDo1NjoxMy42NDI2NjkiLCAiZXhwaXJlcyI6ICIyMDEzLTExLTIzVDAwOjU2OjEzWiIsICJpZCI6ICJwbGFjZWhvbGRlciJ9LCAic2VydmljZUNhdGFsb2ciOiBbXSwgInVzZXIiOiB7InVzZXJuYW1lIjogImFkbWluIiwgInJvbGVzX2xpbmtzIjogW10sICJpZCI6ICJjY2MwMjJkZGNhMzU0N2NiYmIxMmZmNTViNTZkOGI2OCIsICJyb2xlcyI6IFtdLCAibmFtZSI6ICJhZG1pbiJ9LCAibWV0YWRhdGEiOiB7ImlzX2FkbWluIjogMCwgInJvbGVzIjogW119fX0xgf8wgfwCAQEwXDBXMQswCQYDVQQGEwJVUzEOMAwGA1UECBMFVW5zZXQxDjAMBgNVBAcTBVVuc2V0MQ4wDAYDVQQKEwVVbnNldDEYMBYGA1UEAxMPd3d3LmV4YW1wbGUuY29tAgEBMAcGBSsOAwIaMA0GCSqGSIb3DQEBAQUABIGAqoSsewZ+ceYq1JXnu9OVvTJj+Aljm+rUio1biXow72iZ+MVBJKbKvlT4-2DFPC1PrCOErpX2jJ7HuiASSaBgAcROT+LmV3KNnHa+p9DCtgSBGRN7qHJpnQBXgs3tz4ZMVi3AB9i1mOmVHxeVKVfiQWt1zyis7OZPG-PZRq1DohQ=");
httppost.setEntity((params1));
// Execute HTTP Post Request
Log.i("TAG", "pushing your data");
HttpResponse response = httpclient.execute(httppost);
Log.i("TAG", "Sucessful " + response.getParams());
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String jsonresponse = reader.readLine();
JSONTokener tokener = new JSONTokener(jsonresponse);
try {
JSONArray finalResult = new JSONArray(tokener);
Log.i("TAG", "Sucessfully communicated on server");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}catch (IOException e) {
Log.e("", "IOException " + e.toString());
Log.i("", "The server refused again! ");
// TODO Auto-generated catch block
}
}
But I'm getting this Error
org.json.JSONException: Value{
"error": {
"message": "The request you have made requires authentication.",
"title": "Not Authorized",
"code": 401
} }
I'm expecting that the token I've passed will authorize me from adding new user.
That's why I don't understand the error.
Anyone, please help. Any idea how to solve this?
Apart from checking that you have the Admin role for the target project (e.g. when you request the auth token, you need to specify the tenant ID), also make sure that the auth token is not expired.
Also I believe you should use
"name", "Lou Mary"
instead of
"username", "Lou Mary"
I've never really used http requests in Java, I'm trying to make a request that would basically recreate this http://supersecretserver.net:8080/http://whateverwebsite.com
This server takes whatever website and returns only the text of the page in the body of the response.
The code is as follows:
public String getText(String webPage) throws ParseException, IOException{
HttpResponse response = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI("http://supersecretserver.net:8080/" + "http://www.androidhive.info/2012/01/android-text-to-speech-tutorial/"));
response = client.execute(request);
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String responseBody = "No text found on webpage.";
int responseCode = response.getStatusLine().getStatusCode();
switch(responseCode) {
case 200:
HttpEntity entity = response.getEntity();
if(entity != null) {
responseBody = EntityUtils.toString(entity);
}
}
System.out.println("Returning Response..");
System.out.println(responseBody);
return responseBody;
}
It seems to get stuck on
response = client.execute(request);
I'm not sure what the problems is, any insight would be helpful.
Seems likely that your HttpClient is not timing out, you can set a timeout value by following this example (from http://www.jayway.com/2009/03/17/configuring-timeout-with-apache-httpclient-40/)
You just to have to consider a timeout value that makes sense for you.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpParams params = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, connectionTimeoutMillis);
HttpConnectionParams.setSoTimeout(httpParams, socketTimeoutMillis);
Also as your HttpClient is not connecting (since it's getting stuck) you should also take into consideration why is that happening (maybe you need to configure a proxy?)
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://www.google.com");
client.execute(request);//it fails at this line
Log.e("yo", "yo");
} catch (Exception e) {}
Have anyone figured out the problem please as I am experiencing the same issue.
My device is connected to the same network, pasting the URL in browser works however using HTTP doesn't.
try HttpPost method
Declare INTERNET PERMISSION IN manfiest file
httpclient=new DefaultHttpClient();
HttpPost httppost=new HttpPost(URL);
HttpResponse res = null;
try {
res = httpclient.execute(httppost);
System.out.println("asa "+res);
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
Did you forget to add
<uses-permission android:name="android.permission.INTERNET" />
to your AndroidManifest.xml?
Are you running it on the same thread as your UI? You have to use separate thread for any network connection to prevent UI Blocking. You need to use AsyncTask in this case; and obviously, android Internet permission is needed.