Android Http xml error - java

I would like to get in string one page xml response, but my script always shutdown, anybody has an idea what is the problem with that? In the manifest i take:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Code:
String URL = "http://sample.com/test.xml";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
try {
response = httpclient.execute(httppost);
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
} catch (IOException e1) {
// TODO Auto-generated catch block
}
HttpEntity r_entity = response.getEntity();
try {
xmlString = EntityUtils.toString(r_entity);
String s = "2";
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

You can't do networking on the UI Thread (the main thread).
You will need to do your network call on another thread. Use one of the following:
ASyncTask
Loader
Service with Thread
Better yet, do this tutorial:
http://developer.android.com/training/basics/network-ops/index.html
This tutorial explains the basic tasks involved in connecting to the
network, monitoring the network connection (including connection
changes), and giving users control over an app's network usage. It
also describes how to parse and consume XML data.

Related

How to send java object as post parameter with server bean mapping

I am currently writing a client to access rest service, the server rest call accepts one parameter of type java object with #BeanParam annotated.
How do i send data from Apache HTTP client to achieve this.
Below is my server and client code
Server code
#Override
#POST
#Path("/generate_verify_otp/{issuername}")
#Produces("application/x-www-form-urlencoded")
#Consumes("application/x-www-form-urlencoded")
public MultivaluedMap<String, Object> generateVerifyOTP(#BeanParam QPayOTPRequest qpayOTPRequest, #PathParam("issuername")) {
some business logic
}
Client code
public void getOtp(HttpServletRequest request){
QPayOTPRequest qpayOTPRequest = formatDataForOtp(request);
StringWriter writer = new StringWriter();
JsonGenerator jgen;
try {
jgen = new JsonFactory().createJsonGenerator(writer);
jgen.setCodec(new ObjectMapper());
jgen.writeObject(qpayOTPRequest);
jgen.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(writer.toString());
String url = "sdfghjklfghjk;
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
try {
HttpPost post = new HttpPost(url);
StringEntity entiry = new StringEntity(writer.toString());
post.addHeader("content-type", "application/x-www-form-urlencoded");
post.setEntity(entiry);
HttpResponse response = httpClient.execute(post);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
How to i send parameters from client so that it maps to #beanparam object.

JSON io writer delete JSONObject on Android

I'm currently using the library JSON-io. I created a desktop application which when a person want to log in in the system send an JSONObject with his username and password. Then the server send back the response if the person is allowed or not (also a JSONObject). Until here everything works fine.
Now i want to make an Android app. I take the same code than before for login but the application crashes.
The code for login is launch from an AsyncTask and i put the permission to access to Internet to the Manifest.
I perform some testing and it occurs that the method write of JSONWriter "delete" my JSON because on the server side he receives this : {}. I tried to hardcode the JSONObject on the server side (the server's code works fine because we can use the desktop app) but this time the readObject on the android App receives also {}.
We tried to send jsonObject.toString() and this time it worked (except that the server isn't configured to handle a string).
Do anyone knows why on android the two methods write and readObject are deleting the JSON ?
Thank you.
EDIT:
Here the code i wrote:
On the android App
protected Boolean doInBackground(Void... params) {
// 3 : create a JSON object and send it to server for verification
JSONObject loginJS = new JSONObject();
try {
loginJS.put("type", Type.LOGIN); // Type is an enum
loginJS.put("username", userName);
loginJS.put("hash", mPassword);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
User user = new User();
System.out
.println("User created and ready to connect to the spu for login");
user.connexionToSPU(); // This method works
System.out.println("LoginJS = "+loginJS.toString()); At this point the print of the JSON is fine we have {"type":"Login", ....}
user.sendToSPU(loginJS); //This is where there's a problem
// 4 : wait response
JSONObject loginResponseJS = user.receiveFromSPU(); // And when i hard code the JSON on the server side receiveFromSPU get a empty JSON
Method connexionToSPU:
public void connexionToSPU() {
jswSPU = null;
jsrSPU = null;
Socket socket = null;
try {
socket = new Socket(prop.readPropertiesXML("IP_adress_server"),
Integer.parseInt(prop.readPropertiesXML("port_server")));
} catch (NumberFormatException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
jswSPU = new JsonWriter(socket.getOutputStream());
jsrSPU = new JsonReader(new BufferedInputStream(socket.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
sendToSPU method
public void sendToSPU(JSONObject json) {
try {
jswSPU.write(json);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ReceiveFromSPU method
public JSONObject receiveFromSPU() {
JSONObject json = null;
try {
json = (JSONObject) jsrSPU.readObject();
System.out.println("JSON FROM THE SERVER : "+json.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}
Hope it will be sufficiently clear.
Thank you

HTTP POST does not work in Android

I encountered the same problem - you need to add the user to the database with the aid of the POST. I did everything the same as in IPhone - but my android implementation for some reason does not work - users on the server are not saved.
Please tell me what is the problem? I hope for your help.
Android HTTP POST :
public void postData() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://&&&&&&&.dk/accounts/save_user/");
try {
facebookUserInfo = new JSONObject(mFb.request("me"));
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
try {
nameValuePairs.add(new BasicNameValuePair("fbuid", facebookUserInfo.getString("id")));
nameValuePairs.add(new BasicNameValuePair("first_name", facebookUserInfo.getString("first_name")));
nameValuePairs.add(new BasicNameValuePair("last_name ", facebookUserInfo.getString("last_name")));
System.out.println(facebookUserInfo.getString("id")+" "+facebookUserInfo.getString("first_name")+" "+facebookUserInfo.getString("last_name"));
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
System.out.println(response.getEntity()+" "+response.getStatusLine());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
IPhone HTTP POST :
NSURL *url = [NSURL URLWithString:#"http://&&&&&&&&&.dk/accounts/save_user/"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
//[request setPostValue:myAnnotation.google_id forKey:#"google_id"];
[request setPostValue:fbuid forKey:#"fbuid"];
[request setPostValue:_fbFirstName forKey:#"first_name"];
[request setPostValue:_fbLastName forKey:#"last_name"];
[request startSynchronous];
NSError *error = [request error];
if (!error) {
NSString *response = [request responseString];
NSLog(#"%#",response);
}
I've pulled your solution into an answer to help others in the future.
The problem is in this line.
nameValuePairs.add(new BasicNameValuePair("last_name ", facebookUserInfo.getString("last_name")));
Problems are caused by a gap(space) in the key last_name. so to fix this method EntityUtils.toString(httpPost.getEntity() returns a result row
fbuid=100004343290749&first_name=Proba&last_name+=Proba
after correction
fbuid=100004343290749&first_name=Proba&last_name=Proba

Android app using HttpURLConnection crashes at connect()

I have a following piece of code, basically copy-pasted from examples as I am new to Java and Android (not to programming):
URL vurl = new URL(voteurl); //vuteurl is a string containing a proper URL
HttpURLConnection hc;
hc=null;
hc = (HttpURLConnection)vurl.openConnection();
hc.setRequestMethod("GET");
hc.setDoOutput(true);
hc.setReadTimeout(10000);
hc.connect();
On the line "hc.connect();" the application crashes and Android informs me that it had been stopped.
Adding android.permission.INTERNET to the permisions used by the app did not help.
OK, turns out Android doesn't like network operations in the main thread.
Doing a request in a separate thread does the trick. Thanks guys for Your help!
URL vurl = null;
try {
vurl = new URL(voteurl);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} //vuteurl is a string containing a proper URL
HttpURLConnection hc;
hc=null;
try {
hc = (HttpURLConnection)vurl.openConnection();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
hc.setRequestMethod("GET");
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
hc.setDoOutput(true);
hc.setReadTimeout(10000);
try {
hc.connect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

How to append listview items from the Internet

I'm still struggling to find an answer to my question. I want to download 3 strings for each item in the listview to the phone. I know how to get all the data from the server, just not how to append the data to the litview, I'm really annoyed and this problem is dragging me down.
My Code:
public class ChatService extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chatservice);
try {
ContactsandIm();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
CheckLogin();
private void CheckLogin() {
// TODO Auto-generated method stub
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
/* login.php returns true if username and password is equal to saranga */
HttpPost httppost = new HttpPost("http://gta5news.com/login.php");
try {
// Execute HTTP Post Request
Log.w("HttpPost", "Execute HTTP Post Request");
HttpResponse response = httpclient.execute(httppost);
String str = inputStreamToString(response.getEntity().getContent())
.toString();
Log.w("HttpPost", str);
if (str.toString().equalsIgnoreCase("true")) {
Log.w("HttpPost", "TRUE");
try {Thread.sleep(250);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//put intent here(21/3/12);
} else {
Log.w("HttpPost", "FALSE");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}
private void ContactsandIm() throws URISyntaxException, ClientProtocolException, IOException {
// TODO Auto-generated method stub
BufferedReader in = null;
String data = null;
HttpClient get = new DefaultHttpClient();
URI website = new URI("http://www.gta5news.com/test.php");
HttpGet webget = new HttpGet();
webget.setURI(website);
HttpResponse response = get.execute(webget);
Log.w("HttpPost", "Execute HTTP Post Request");
in = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));
//now we'll return the data that the PHP set from the MySQL Database.
if (in.equals("True")); {
Toast.makeText(this,"yay", Toast.LENGTH_LONG).show();
}
}
// end bracket for "ContactsandIm"
private void showToast(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}
Use an ArrayAdapter on your list, and add items to this adapter, then call notifyDatasetChanged on it, and zou
First of all when we connect to Server using the Network Threads, then you should go for AsyncTask or Handlers. Which is specially used for handling such Threads.
ListView can be created by using default Listview ans also the Custom Listview where we can design our own Row design in the Row.xml and the same design will be used for all the rows.
If you want move forward or go for some advanced Listview then even we can use 'n' number of designs for different rows.
Here in your case, You should use a AsyncTask for fetching the data and use the Listview for displaying rows.
You can get more information from the below link.
https://docs.google.com/leaf?id=0B2qCFbmeiTFxN2ViZjVlOTUtNmY3ZS00NThhLTg3N2UtYjVkYjgyM2Y4MWUy&hl=en&authkey=COeP8JYN

Categories