In Http Post, the values are not send to server. I got unknownhostexception at following line.HttpResponse rs=httpclient.execute(httppost);
http Coding:
HttpClient httpclient=new DefaultHttpClient();
HttpPost httppost=new HttpPost("http://www.mysite.com/fasttrack/androidapps.php");
httppost.setEntity(new UrlEncodedFormEntity(data));
appendLog("7)Value Encoded to url successfully");
HttpResponse rs=httpclient.execute(httppost); // unknownhostexception got
I added <uses-permission android:name="android.permission.INTERNET"/> in Manifestfile also...
Note : this codings works fine before I added log file codings...
my Log File coding is below:
public void appendLog(String text)
{
//File logFile = new File("alog.txt");
File logFile = new File("sdcard/alog.file");
if (!logFile.exists())
{
try
{
logFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(text);
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Sometimes the android emulator's browser stops working. So, try to restart your emulator from cmd like this,
run->cmd->your_sdk_path->tools->emulator -avd avd_name -dns-server 8.8.8.8
Related
I try to get some Data from a WebService using KSoap2.
The WebService responses a very large XML-File so while I'm doing the HttpTransportSE.call() I get an ouOfMemory Exception.
Is it possible to get a snipped response from a Soap Webservice?
Or is there a way to write it directly in a file on the device?
This is my Class to get the Data:
public static SoapObject GetItemData()
{
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME_ITEM_DATA);
request.addProperty("Company", company);
request.addProperty("SerialNumber", serialId);
itemEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
itemEnvelope.dotNet = true;
itemEnvelope.setOutputSoapObject(request);
AndroidHttpTransportSE androidHttpTransport = new AndroidHttpTransportSE(URL);
androidHttpTransport.debug = true;
Log.d("==ITEM_URL==", URL);
try
{
androidHttpTransport.call(SOAP_ACTION_ITEM_DATA, itemEnvelope);
Log.d("==ItemVerbindung==", "Verbindung aufgebaut");
}
catch (Exception e)
{
e.printStackTrace();
Log.d("==ItemVerbindung==", "HTTPCALL nicht ausgeführt");
}
try
{
itemResult = (SoapObject)itemEnvelope.getResponse();
Log.d("==ItemResponse==", "PropertyCount: "+itemResult.getPropertyCount());
}
catch(ClassCastException e)
{
itemResult = (SoapObject)itemEnvelope.bodyIn;
}
catch (SoapFault e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
if(itemResult != null)
{
return itemResult;
}
return null;
}
I have also coppied the HttpTransportSE.java and manipulated it to write directly in a file. But there I get an unvalid Token error.
I remember to have seen this problem before:
Two Recommendations:
1) Save your SOAP XML stream directly to disk as you download it. Don't store it in memory.
2) Parse it using a SAX-style parser, where you don't load the whole DOM in memory, but rather parse it in chunks.
EDIT: Check this -> Very large SOAP response - Android- out of memory error
I found a solution without using the KSoap2 Library.
Here is the code:
try {
java.net.URL url = new java.net.URL(URL);
HttpURLConnection rc = (HttpURLConnection) url.openConnection();
rc.setRequestMethod("POST");
rc.setDoOutput(true);
rc.setDoInput(true);
rc.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
rc.addRequestProperty("User-Agent", HTTP.USER_AGENT);
rc.setRequestProperty("SOAPAction", SOAP_ACTION_ITEM_DATA);
OutputStream out = rc.getOutputStream();
Writer wout;
wout = new OutputStreamWriter(out);
wout.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
wout.write("<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">");
wout.write("<soap:Body>");
wout.write("<GetItemData2 xmlns=\"http://localhost/HSWebBL\">");
wout.write("<Company>" + company + "</Company>");
wout.write("<SerialNumber>" + serialId + "</SerialNumber>");
wout.write("</GetItemData2>");
wout.write("</soap:Body>");
wout.write("</soap:Envelope>");
wout.flush();
wout.close();
rc.connect();
Log.d("==CLIENT==", "responsecode: " + rc.getResponseCode() + " " + rc.getResponseMessage());
InputStream in = new BufferedInputStream(rc.getInputStream(), BUFFER_SIZE);
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I use a SAXParser to parse the InputStream.
In that way I don't get an outOfMemoryException and no parsing error anymore.
I have written a Android program to upload a file to server by HTTP POST.
Earlier its was working fine but I don't know why it is not working now.
I am testing this with my Android Device.
I Have just checked that It is working fine with emulator.
When I open that link in browser, Then it is still working fine and open correctly.
Do any body can tell me what could be the problem???
I am getting this error: (No Address associated with hostname)
10-07 04:28:14.410: I/System.out(1280): executing request POST http:////path/to/my/server//api/index.php/match HTTP/1.1
10-07 04:28:14.450: W/System.err(1280): java.net.UnknownHostException: Unable to resolve host "//path/to/my/server/": No address associated with hostname
Here is my code...
private class UploadFilesTask extends AsyncTask<File, Void, Void> {
#Override
protected Void doInBackground(File... arg0) {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
enter code here
// I have not shown my REAL server address due so some restriction, So assume below URL is correct
HttpPost httppost = new HttpPost("http://path/to/my/server/"); //Assume path is correct
//File file = new File("/mnt/sdcard/DCIM/Camera/01.jpg");
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(arg0[0], "image/jpeg");
mpEntity.addPart("userfile", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = null;
try {
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
try {
//audioFilename = EntityUtils.toString(resEntity);
System.out.println(EntityUtils.toString(resEntity));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (resEntity != null) {
try {
resEntity.consumeContent();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
httpclient.getConnectionManager().shutdown();
return null;
}
}
Try the following
Delete your AVD
Shut down Eclipse
Created the AVD via the command line (e.g. android create avd -n my_android1.5 -t 2)
Launched it from the command line with the option -dns-server 8.8.8.8 (e.g. emulator -avd my_android1.5 -dns-server 8.8.8.8)
p.s. Make sure you didn't delete the internet permission in your manifest file by accident. Also, while you are it, check and make sure the address work on your android browser.
Try flush DNS. (in windows: ipconfig /flushdns)
Or change DNS provider.
Maybe there is a 2 '/' simbols in url ? "...server//api..." this must be like this "...server/api..."
I am trying for post data(username and password in JSON format for login) from android application to php server - drupal cms website using HttpUrlConnection .
Here is my code , For login.
I am getting this response:
java.net.ProtocolException: OutputStream unavailable because request
headers have already been sent!
I have searched on google & other stackoverflow questions but cant find any solution to my problem. So Please Help.
Thanks for listening.
HttpURLConnection httpcon = null;
int status = 0;
try {
httpcon = (HttpURLConnection) ((new URL("my URL here").openConnection()));
httpcon.setDoOutput(true);
httpcon.setRequestProperty("Content-Type", "application/json");
httpcon.setRequestProperty("Accept", "application/json");
httpcon.setRequestMethod("POST");
status = httpcon.getResponseCode();
httpcon.getHeaderFields();
System.out.println("===================>httpcon.getHeaderFields()"+httpcon.getHeaderFields());
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
httpcon.connect();
byte[] outputBytes = "{'username':'uname','password':'pass'}".getBytes("UTF-8");
OutputStream os = httpcon.getOutputStream();
os.write(outputBytes);
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return status;
You call httpcon.getResponseCode() and httpcon.getHeaderFields() in the first part of your code. As mentioned in the javadoc for HttpUrlConnection, this causes the HTTP request to be executed. This makes sense, because to read the response header fields you need a response, and to get a response you have to issue the request.
You then do the output stream stuff, which fails because the request has already been sent.
To make this work, you need to re-order your code so that all the request stuff is set up before you access the response stuff. Something along these lines:
byte[] outputBytes = "{'username':'uname','password':'pass'}".getBytes("UTF-8");
try {
HttpURLConnection httpcon = (HttpURLConnection) ((new URL("my URL here").openConnection()));
//prepare the request
httpcon.setDoOutput(true);
httpcon.setRequestProperty("Content-Type", "application/json");
httpcon.setRequestProperty("Accept", "application/json");
httpcon.setRequestMethod("POST");
httpcon.connect(); // May not be needed
OutputStream os = httpcon.getOutputStream();
os.write(outputBytes);
//get the response
status = httpcon.getResponseCode();
httpcon.getHeaderFields();
System.out.println("===================>httpcon.getHeaderFields()"+httpcon.getHeaderFields());
} //catch block left out
I have the following code which I use to send a request to the server.
String inputXML = createInputXML(searchText);
HttpClient httpclient = new DefaultHttpClient();
String url = "http://mysite.com/action";//Works fine if I use IP address directly,for eg:http://1.2.3.4/action
HttpPost httppost = new HttpPost(url);
HttpResponse response=null;
StringEntity se = null;
try {
se = new StringEntity(inputXML, HTTP.UTF_8);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
se.setContentType("text/xml");
httppost.setHeader("Content-Type","application/xml;charset=UTF-8");
httppost.setEntity(se);
try {
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
When I run the program on emulator I am getting a UnKnownHostException on the line
response = httpclient.execute(httppost);
If I use the ip address directly instead of host name,the request is sent correctly.
Please note the following points:
I am using Android 2.3.3
I have added <uses-permission android:name="android.permission.INTERNET"></uses-permission> in the manifest xml
Proxy settings are updated in the emulator's APN.
Using the browser in the emulator I can access a website with their host names.
Any idea why this is causing an issue?
Please make sure, you followed all steps 1-4 user700284 described in his Question.
HttpClient client = new DefaultHttpClient();
//Get the default settings from APN (could be also hard coded stuff)
String proxyHost = android.net.Proxy.getDefaultHost();
int proxyPort = android.net.Proxy.getDefaultPort();
//Set Proxy params of client, if they are not the standard
if (proxyHost != null && proxyPort > 0) {
HttpHost proxy = new HttpHost(proxyHost, proxyPort);
client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
}
HttpGet request = new HttpGet("http://www.google.com");
The url has nothing to do with the line
se = new StringEntity(inputXML, HTTP.UTF_8);
are you sure it is this line?
I m implementing android app in that I m working on web api. Sometimes my app gets connected to webserver but sometimes it throws exception as java.net.UnknownHostException: Host is unresolved: webservername.com:80. I m fetching json response from api.
I m using fetching code as following:
String queryResult = null;
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
try {
request.setURI(new URI(archiveQuery));
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//HttpResponse response = client.execute(request, new BasicResponseHandler());
try {
queryResult = client.execute(request, new BasicResponseHandler());
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I think it's a DNS issue of your server, according to your comments. Sometimes you ping, sometimes you don't, but on your browser it always work? Surely it's a server connectivity issue.
The Answer is really very simple. You need to Restart the emulator.Check out this
Just restart adb, find adb.exe in your adt bundle and double click it. Some shit will happen on command prompt, and there you go, restart your emulator and it should work fine,