Why I'm not getting any response from server in this code - java

public String POST(String url){
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("UserName","example#gmail.com");
jsonObject.accumulate("Password","123456!");
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// ** Alternative way to convert Person object to JSON string usin Jackson Lib
// ObjectMapper mapper = new ObjectMapper();
// json = mapper.writeValueAsString(person);
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
Toast.makeText(getBaseContext()," text",Toast.LENGTH_SHORT).show();
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result;
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
// Toast.makeText(getBaseContext(), "post invoked", Toast.LENGTH_SHORT).show();
return POST(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Data Sent!"+result+" don", Toast.LENGTH_LONG).show();
}
}
I tried to invoke this POST method from an object of HTTPAsyncTask class, with targeted url passed. But the Toast execeuted in OnPostExecute() popping up with the message "Data sent!Done", which tells that value of 'result' variable is null. And in log cat it is showing"I'm getting feedback from logcat that "Request time failed,Java.net.socketException:Addres family not supported by protocol". What would the fault? Could anyone please fix this***

The URL is lacking the protocol part. Try
http://devcare.dyndns.info:85/WCFServices/UserAuthServices.svc/Login
otherwise devcare.dyndns.info will be mistaken as the protocol.

Try adding this to AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
And please catch this exception:
catch(SocketException se)
{
Log.e("Exception ---- : " , "Error on execute??" + se.getMessage());
se.printStackTrace();
}

Related

doInbackground of asyncktask is not called

This url is executed when a button is clicked
new HttpAsyncTasks().execute("http://www.demo.com/xyz");
this is the asynctask for the above execution
private class HttpAsyncTasks extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return POSTS(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "successfull!", Toast.LENGTH_LONG).show();
//call main activity activity upon successful registration
Intent callMain = new Intent(getApplicationContext(),
MainActivity.class);
startActivity(callMain);
}
}
The doInbackground of the above never gets executed but the onPostExecute method does.
this is the POSTS method called in doInbackground
public String POSTS(String url){
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("xyz", "xyz");
jsonObject.accumulate("amount", "800");
jsonObject.accumulate("demo", "demo");
jsonObject.accumulate("demo2", demo2);
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// ** Alternative way to convert Person object to JSON string usin Jackson Lib
// ObjectMapper mapper = new ObjectMapper();
// json = mapper.writeValueAsString(person);
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result;
}
Please what could be wrong?
Can you try this with way. It's checking your POSTS method.
If toast show empty line, your error in POSTS method on WebProcess.
private class HttpAsyncTasks extends AsyncTask<String, Void, String> {
private String myResult="check";
#Override
protected String doInBackground(String... urls) {
try
{
myResult = POSTS(urls[0]);
}
catch(Exception e)
{
return e;
}
return myResult;
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
/* other codes */
}
}
Your POSTS(urls[0]) call must be giving an exception and when it does the rest of the code is skipped and it bypasses your toast. Try removing exception you can find it in logcat.

What value should I use for Content-Length of an POST HTTP request?

I am trying to send HTTP request. Currently I am stuck on adding Content-Length property: I have
httpPost.addHeader("Accept", "application/json");
httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
httpPost.addHeader("Content-Length", ""+json.length() );
If i comment last line (content-length) server returns me error that I miss smth, I last line stays uncommented - then I catch an exception when trying to do
HttpResponse httpResponse = httpclient.execute(httpPost);
Please, tell me what am I doing wrong with setting headers.
PS I am sending easy JSON object
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("phone", phone);
My full code snippet of post metod:
public static JSONObject POST(String url, String phone){
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "";
// 3. build jsonObject
Log.d("ANT", "JSONObject jsonObject = new JSONObject(); PHONE:"+phone);
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("phone", phone);
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
Log.d("ANT", "json"+json.length());
// 7. Set some headers to inform server about the type of the content
httpPost.addHeader("Accept", "application/json");
httpPost.addHeader("Content-Type", "application/json;");
// httpPost.addHeader("Content-Length", ""+json.length() );
// 8. Execute POST request to the given URL
Log.d("ANT", "httpPost:"+getStringFromInputStream(httpPost.getEntity().getContent()));
for (Header s : httpPost.getAllHeaders())
Log.i("ANT", "header::"+s.getName() + ":"+s.getValue());
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
Log.d("ANT", "httpResponse.getEntity().getContent();");
// 10. convert inputstream to string
if (inputStream != null) {
result = getStringFromInputStream(inputStream);
Log.d("ANT", "getStringFromInputStream : "+result);
JSONObject obj = new JSONObject(result);
Log.d("ANT", "JSONObject");
return obj;
}
else
result = "Did not work!";
} catch (ClientProtocolException e) {
Log.d("ANT", "ClientProtocolException : "+ e.getLocalizedMessage());
} catch (IOException e) {
Log.d("ANT", "IOException:"+ e.getLocalizedMessage());
} catch (Exception e) {
Log.d("ANT", "Exception:"+ e.getLocalizedMessage());
}
// 11. return result
return null;
}
Can you elaborate on what the server error code is and a stack trace when the exception occurs?
Edit:
I tried some part of your code. I did not set the Content-Length (since this should be done automatically):
public class App
{
public static void main( String[] args )
{
post("http://www.baidu.com","+8912345");
}
public static JSONObject post(String url, String phone){
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("phone", phone);
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.addHeader("Accept", "application/json");
httpPost.addHeader("Content-Type", "application/json;");
// 8. Execute
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
} catch (ClientProtocolException e) {
System.out.println("ClientProtocolException : "+e.getLocalizedMessage());
} catch (IOException e) {
System.out.println("IOException:"+ e.getLocalizedMessage());
} catch (Exception e) {
System.out.println("Exception:"+ e.getLocalizedMessage());
}
return null;
}
}
I used wireshark and could verify that the following request is going to baidu:
POST / HTTP/1.1
Accept: application/json
Content-Type: application/json;
Content-Length: 20
Host: www.baidu.com
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.3.6 (java 1.5)
{"phone":"+8912345"}
This shows that the request is sent properly, which means the client side seems to be fine. That's why I would suggest to check the server side for errors. As I already mentioned I think you should use tcpdump or wireshark to check the traffic between client and server. This might give you a better understanding of what is going wrong.

Fill form from Java Android and send Request

I'm trying to fill form from Java program for Android and send request to the server. First I tried to use a Selenium for Android, but I failed to start it, then I found to many examples about, how to use HttpPost etc.., but the action of the form is:
form name="mainform" method="POST" action="/system/boxuser_edit.lua"
So I found the following code, and I tried to many possible combination, but without success
class SendPostReqAsyncTask extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
String paramUsername = params[0];
String paramPassword = params[1];
HttpClient httpClient = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(httpClient.getParams(),100000);
HttpConnectionParams.setSoTimeout(httpClient.getParams(), 100000);
String SID = "xxxxxxxxx";
HttpPost httpPost = new HttpPost("http://fritz.box/system/boxuser_edit.lua?sid="+SID+"=new");
BasicNameValuePair emailBasicNameValuePair = new BasicNameValuePair("user", paramUsername);
BasicNameValuePair passwordBasicNameValuePair = new BasicNameValuePair("password", paramPassword);
// We add the content that we want to pass with the POST request to as name-value pairs
//Now we put those sending details to an ArrayList with type safe of NameValuePair
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
nameValuePairList.add(usernameBasicNameValuePair);
nameValuePairList.add(passwordBasicNameValuePair);
try {
// UrlEncodedFormEntity is an entity composed of a list of url-encoded pairs.
//This is typically useful while sending an HTTP POST request.
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList);
// setEntity() hands the entity (here it is urlEncodedFormEntity) to the request.
httpPost.setEntity(urlEncodedFormEntity);
try {
// HttpResponse is an interface just like HttpPost.
//Therefore we can't initialize them
HttpResponse httpResponse = httpClient.execute(httpPost);
// According to the JAVA API, InputStream constructor do nothing.
//So we can't initialize InputStream although it is not an interface
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
System.out.println("First Exception caz of HttpResponese :" + cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out.println("Second Exception caz of HttpResponse :" + ioe);
ioe.printStackTrace();
}
} catch (UnsupportedEncodingException uee) {
System.out.println("An Exception given because of UrlEncodedFormEntity argument :" + uee);
uee.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(givenUsername, givenPassword);
}
i have just bunch of questions before we discuss your code because what you did here seems to be correct.
First of all did you request a permission to access network in the manifest file?
if it's not this is how you do it:
add this line of code to your androidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
But before that you have to check that the link you are passing to the HttpPost Object is working, you can use a web browser to test it, because i just did that right now and it seems that it doesn't work!!

Get data from json and org.json.JSONException is thrown

Following json will be received but through the http://localhost/getData.php but exception is thrown
{"username":"not found","password":null}
Log I received
02-19 17:31:54.745: E/JSON Parser(5277): Error parsing data org.json.JSONException: End of input at character 0 of
02-19 17:31:59.185: E/JSON Parse(5277): ERROR
Following code is the method where exception throw
#Override
protected String doInBackground(String... url){
try{
String resultText = "";
EditText edit = (EditText)findViewById(R.id.text_box);
id = edit.getText().toString();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id",id));
JSONObject json = jsonParser.HttpRequest("http://localhost/getData.php", params);
resultText = json.getString("username");
}catch(Exception e){
e.printStackTrace();
Log.e("JSON Parse","ERROR");
}
return "";
}
public class SimpleJsonParser {
public SimpleJsonParser(){
}
public JSONObject HttpRequest(String url, List<NameValuePair> params){
InputStream input = null;
JSONObject jObj = null;
String json = "";
String line;
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
paramsString = URLEncodedUtils.format(params,"utf-8");
url += "?" + paramsString;
HttpGet httpGet = new HttpGet(url);
try{
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
HttpEntity entity = response.getEntity();
input = entity.getContent();
BufferedReader reader =
new BufferedReader(new InputStreamReader(input));
while((line = reader.readLine())!=null){
builder.append(line);
}
json = builder.toString();
} else {
Log.e("JSON Parser","Failed to download file");
}
}catch(ClientProtocolException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
try {
jObj = new JSONObject(json);
input.close();
} catch (Exception e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
}
Anything wrong with my code? The code I provided is where exception throws occur
From what you mentioned, it appears that you are doing this via an emulator.
Emulator may not be able to access http://localhost//. You can try access using, loopback address or the ip address.
You never verify that you actually have received anything after reading from the stream returned from the HttpEntity. That exception is telling you there's no input at character 0 (The first character) - you have nothing to parse; it's an empty string. Nothing was ever appended to your StringBuilder.
public static void main(String[] args) throws JSONException
{
String json = "{\"username\":\"not found\",\"password\":null}";
JSONObject jObj = new JSONObject(json);
}
Throws no such exception. Often writing a small test case will point you in the right direction.
As others have mentioned, this is probably because you are using the wrong URL or maybe your parameters? Since you're getting back a 200 OK you're obviously connecting to a webserver and getting a response ... I'd check to see if that PHP is working as you expect.
Inside simpleJarsonParser class, I replace the following code
HttpClient httpClient = new DefaultHttpClient();
to
DefaultHttpClient httpClient = new DefaultHttpClient();
and it works. And of course I have replace localhost to 10.0.2.2 as I'm using xampp and android emulator.

Android: send post that has no response

In my app, I need to send all sorts of POST requests to a server. some of those requests have responses and others don't.
this is the code I'm using to send the requests:
private static final String TAG = "Server";
private static final String PATH = "http://10.0.0.2:8001/data_connection";
private static HttpResponse response = null;
private static StringEntity se = null;
private static HttpClient client;
private static HttpPost post = null;
public static String actionKey = null;
public static JSONObject sendRequest(JSONObject req) {
try {
client = new DefaultHttpClient();
actionKey = req.getString("actionKey");
se = new StringEntity(req.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_ENCODING, "application/json"));
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post = new HttpPost(PATH);
post.setEntity(se);
Log.d(TAG, "http request is being sent");
response = client.execute(post);
Log.d(TAG, "http request was sent");
if (response != null) {
InputStream in = response.getEntity().getContent();
String a = convertFromInputStream(in);
in.close();
return new JSONObject(a);
}
} catch (UnsupportedEncodingException e) {
Log.d(TAG, "encoding request to String entity faild!");
e.printStackTrace();
} catch (ClientProtocolException e) {
Log.d(TAG, "executing the http POST didn't work");
e.printStackTrace();
} catch (IOException e) {
Log.d(TAG, "executing the http POST didn't work");
e.printStackTrace();
} catch (JSONException e) {
Log.d(TAG, "no ActionKey");
e.printStackTrace();
}
return null;
}
private static String convertFromInputStream(InputStream in)
throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
}
return (sb.toString());
}
This is the code for the AsyncTask class that sends the request:
class ServerRequest extends AsyncTask<JSONObject, Void, JSONObject> {
#Override
protected JSONObject doInBackground(JSONObject... params) {
JSONObject req = params[0];
JSONObject response = Server.sendRequest(req);
return response;
}
#Override
protected void onPostExecute(JSONObject result) {
// HANDLE RESULT
super.onPostExecute(result);
}
}
my problem starts when the server doesn't return a response. the AsyncTask thread stays open even after the work is done because the HTTPClient never closes the connection.
Is there a way to not wait for a response? this is something that will definitely add a lot of overhead to the server since all the Android apps trying to connect to it will keep the connection alive, and will probably cause many problems on the app itself.
Basically, what I'm looking for is a method that will allow me to send to POST message and kill the connection right after the sending of the request since there is no response coming my way.
Just, Set ConnectionTimeOut with HttpClient Object, (Code is for your understanding in your case it may be different)
int TIMEOUT_MILLISEC = 30000;
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient httpclient = new DefaultHttpClient(httpParams);
HttpPost httppost = new HttpPost(url);
httppost.addHeader("Content-Type", "application/json");
Now, It will terminate the Connection after TimeoOut you defined. But be sure this will throw TimeOutException so You have to handle this exception in your HttpRequest.. (Use Try -catch)
EDIT: Or you can use HttpRequestExecutor class.
From class HttpRequestExecutor of package org.apache.http.protocol
protected boolean canResponseHaveBody (HttpRequest request, HttpResponse response)
Decide whether a response comes with an entity. The implementation in this class is based on RFC 2616. Unknown methods and response codes are supposed to indicate responses with an entity.
Derived executors can override this method to handle methods and response codes not specified in RFC 2616.

Categories