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
Related
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.
I am new to websocket, and trying out with few examples. The application I created works fine for sometime say 10 - 15 mins, and from then on, it throws the timeout exception when sendText method is called on websocket session. I changed the value for "org.apache.tomcat.websocket.BLOCKING_SEND_TIMEOUT" to -1 and now it hangs.
could you please help me to resolve this issue.
The code I have written to send the data to websocket is as below:
public void update() {
Dashboard dashboardData = tunnelDataService.getDashboardData();
ObjectWriter ow = new ObjectMapper().writer();
String json = null;
try {
json = ow.writeValueAsString(dashboardData);
} catch (JsonGenerationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (JsonMappingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
synchronized (lock) {
if (session.isOpen()) {
session.getBasicRemote().sendText(json);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I am deploying this application on JBoss EAP 6.3.
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
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.
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();
}