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.
Related
I have a REST API written using Spring boot and i am trying to POST an image and json data through Android client/app where i am using retrofit 2.0 . While doing that , i can see the data appearing but image file is showing as NULL.
can you please help me how to do this or let me know where i am doing the mistake
Server side REST Controller :
#RequestMapping(value = "/v1/producttest", method = RequestMethod.POST)
#ResponseStatus(HttpStatus.CREATED)
public #ResponseBody ProductTestResponse create( #Valid String producttestEntry,
#RequestPart(value = "file", required = false) MultipartFile file) {
LOGGER.info("Creating a product test: {}", producttestEntry);
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map;
try {
map = mapper.readValue(productbuyerEntry, Map.class);
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Android Side code:
MultipartBody.Part reqFile = MultipartBody.Part.createFormData("file", finalFile.getName(), RequestBody.create(okhttp3.MediaType.parse("multipart/form-data"), finalFile));
Call <PostTestresponse> cal = restInterface.Posttest(hj, reqFile);
How can I convert String to HttpInputMessage?
or HttpResponse to HttpInputMessage
Post (return json):
HttpResponse<String> jsonResponse = null;
try {
jsonResponse = Unirest.post(targetURL).header("Accept", "application/json")
.header("Content-Type", "application/json;").body(urlParameters).asString();
} catch (UnirestException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String str = jsonResponse.toString();
HttpInputMessage inputMessage = null;
return inputMessage;
I want convert json to Object
RoutesList routes = new RoutesList();
Post post = new Post(this.url + allRoutes, depoId.toString());
HttpInputMessage inputMessage = null;
try {
inputMessage = post.getResult();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
converter.read(routes.getClass(), RoutesList.class, inputMessage);
} catch (HttpMessageNotReadableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You can wrap the HttpResponse using this class HttpComponentsAsyncClientHttpResponse:
HttpComponentsAsyncClientHttpResponse(HttpResponse httpResponse)
And return it as HttpInputMessag, for example:
return new HttpComponentsAsyncClientHttpResponse(jsonResponse)
this class implement the interface HttpInputMessage.
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 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
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