I am using JaxRS jersey for server and I have deployed it on aws. Http post request to server is working with postman but not with Http post apache client.
Following is my Java for Rest service
#Path("/data")
public class MyResource {
#GET
#Produces(MediaType.APPLICATION_JSON)
public List<trackerdetails> getIt() {
SessionFactory sessionfactory = new Configuration().configure().buildSessionFactory();
Session session = sessionfactory.openSession();
session.beginTransaction();
trackerdetails user = new trackerdetails();
List<trackerdetails> sendlist = (List<trackerdetails>) session.createQuery("from trackerdetails").list();
session.getTransaction().commit();
session.close();
return sendlist;
}
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public trackerdetails putit(trackerdetails track) {
track.setDate(new Date());
SessionFactory sessionfactory = new Configuration().configure().buildSessionFactory();
Session session = sessionfactory.openSession();
session.beginTransaction();
session.save(track);
session.getTransaction().commit();
session.close();
return track;
}
Following is my trackerdetails class
#Entity
#XmlRootElement
public class trackerdetails {
#Id #GeneratedValue(strategy = GenerationType.AUTO)
private int autoid;
private String latitude;
private String longitude;
private String devicename;
private Date date;
public trackerdetails(){
}
public int getAutoid() {
return autoid;
}
public void setAutoid(int autoid) {
this.autoid = autoid;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getDevicename() {
return devicename;
}
public void setDevicename(String devicename) {
this.devicename = devicename;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
Following is my Client side http post request
HttpPost httpPost = new HttpPost("myurl");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("devicename", "vip"));
nvps.add(new BasicNameValuePair("date", "hjksvn"));
nvps.add(new BasicNameValuePair("latitude", "hello"));
nvps.add(new BasicNameValuePair("longitude","hi"));
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
httpPost.setHeader("Cache-Control", "no-cache");
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("Host", "trackertest.herokuapp.com");
CloseableHttpResponse response2 = httpclient.execute(httpPost);
try {
System.out.println(response2.getStatusLine());
System.out.println(response2.toString());
HttpEntity entity2 = response2.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
BufferedReader rd = new BufferedReader(
new InputStreamReader(response2.getEntity().getContent()));
StringBuffer result1 = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result1.append(line);
System.out.println(line);
System.out.println("");
}
System.out.println(result1);
EntityUtils.consume(entity2);
} finally {
response2.close();
}
Following is my error status is 400
Bad Requestdescription The request sent by the client was syntactically incorrect.
Your REST API expects request in JSON format but the way you are constructing request body using NameValuePair will not result in JSON format.
You should make a valid JSON request body either by using some libraries which can convert object into JSON like Jackson or you can manually construct JSON request body and then call your API.
Below is one way of manually constructing JSON request body -
HttpPost httpPost = new HttpPost("myurl");
StringBuilder jsonBody = new StringBuilder();
jsonBody.append("{");
jsonBody.append("\"devicename\" : ").append("\"vip\"").append(",");
// Pass a valid date because on server side, you are using Date object for accepting it
jsonBody.append("\"date\" : ").append("\"2017-09-23\"").append(",");
jsonBody.append("\"latitude\" : ").append("\"vip\"").append(",");
jsonBody.append("\"longitude\" : ").append("\"vip\"");
jsonBody.append("}");
StringRequestEntity requestEntity = new StringRequestEntity(jsonBody.toString(),"application/json","UTF-8");
httpPost.setRequestEntity(requestEntity);
httpPost.setHeader("Cache-Control", "no-cache");
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("Host", "trackertest.herokuapp.com");
// Rest code should remain same
Related
I have a question now i try create a music app on my phone. now I can see my file song But the name shown in the app is the file address instead. and if i want to play the file music in this app. What code do I need to add for get the name of music and play it on my phone? thank a lot
#Override
public void onClick(View view) {
mp.pause();
play.setEnabled(true);
stop.setEnabled(true);
pause.setEnabled(false);
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mp != null) {
mp.stop();
try {
mp.prepare();
} catch (IOException e) {
e.printStackTrace();
}
//mp.release()
play.setEnabled(true);
play.setEnabled(true);
stop.setEnabled(false);
}
}
});
send.setOnClickListener(new View.OnClickListener() {
//List<Intent> intentShareList = new ArrayList<Intent>();
#Override
public void onClick( View view ) {
msgs = msg.getText().toString();
System.out.print("msgs " + msgs);
// make line message
Log.d(TAG, "Txt " + msgs);
Intent shareIntent = new Intent();
String userId = "";
String sendText = "line://ti/p/~" + userId;
//shareIntent = null;
try {
shareIntent = Intent.parseUri(sendText,
Intent.URI_INTENT_SCHEME);
} catch (URISyntaxException e) {
e.printStackTrace();
}
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
shareIntent.putExtra(Intent.EXTRA_TEXT,msgs);
shareIntent.setType("text/plain");
startActivity(shareIntent);
}
});
}
AND
public class Songs {
//private
private String songTitle;
private String songAddress;
public Songs(String title){
//songID = id;
songTitle = title;
}
/*public long getSongID(){
return songId;
*/
public String getSongTitle(){
return songTitle;
}
}
now I can see my file song But the name shown in the app is the file
address instead
I think you are referring to the "Path" of the file, for example:
/storage/emulated/0/song.mp3 (Unix style path)
C:\Songs\song.mp3 (Window style path)
If you would like to parse (find out) the name of the file, use the following code:
String filePath = "/storage/emulated/0/song.mp3";
File f = new File(filePath);
String fileName = f.getName();
// fileName == "song.mp3"
In your case:
public class Songs {
private String title; // renamed from "songTitle"
private String path; // renamed from "songAddress"
private String fileName; // the file name of the song
public Songs(String title, String path){
this.title = title;
this.path = path;
File file = new File(path);
String fileName = f.getName();
this.fileName = fileName;
}
public String getTitle(){
return title;
}
public String getPath(){
return path;
}
public String getFileName(){
return fileName;
}
}
I am working with Spring and javascript. Calling #Controller with XhrHttpRequest Object.
I can see my parameter(JSON string) with Chrome Inspector, but when I call request.getParamter("id") returns null.
Calling part with js
function ajax(url, data, callback, method){
//data is {"id":"system", "password" : "1234"}
var httpRequest;
var afterAction = function(){
if(!httpRequest) {
console.error('can not find httpRequest variable');
return;
}
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
var responseData = httpRequest.responseText;
//alert(JSON.stringify(responseData));
console.log('Result of API call >>>', responseData);
if(typeof callback == 'function') {
callback(JSON.parse(responseData));
}
} else {
alert('There was a problem with the request.');
}
}
}
//=========== LOGIC ============
if (window.XMLHttpRequest) { // Mozilla, Safari, IE7+ ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 6 and older
httpRequest = new ActiveXObject('Microsoft.XMLHTTP');
}
if(!method) method = 'POST';
data = (!!data) ? JSON.stringify(data) : '';
httpRequest.onreadystatechange = afterAction;
httpRequest.open(method.toUpperCase(), url, true);
httpRequest.setRequestHeader("Content-type", "application/json; charset=utf-8");
//httpRequest.setRequestHeader("Content-length", data.length);
//httpRequest.setRequestHeader("Connection", "close");
httpRequest.send(data);
}
receive part with Spring #Controller
#Controller
#RequestMapping(value={"member"}, produces={"application/json"})
#ResponseStatus(value = HttpStatus.OK)
public class MemberController {
/**
* #param request
* #param resp
* #return
* #throws Exception
*/
#RequestMapping(value={"/login"})
public #ResponseBody String login(HttpServletRequest request, HttpServletResponse resp) throws Exception {
System.out.println("Login request");
String id = String.valueOf(request.getParameter("id")); //returns null
String password = String.valueOf(request.getParameter("password")); //returns null
Map<String, String> result = new HashMap<String, String>();
result.put("result", "S");
result.put("message", "login success");
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(result);
}
}
I do not know why parameter becomes null. Thanks.
You need to follow the below steps to accept Json in your controller:
(1) Define UserLogin bean to hold the Json
public class UserLogin {
private String id;
private String password;
//Add getters and setters
}
(2) Change your controller to accept Json & receive the UserLogin bean
#Controller
#RequestMapping(value={"member"}, produces={"application/json"})
#ResponseStatus(value = HttpStatus.OK)
public class MemberController {
#RequestMapping(value={"/login"}, method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody String login(UserLogin userLogin) throws Exception {
System.out.println("Login request");
String id = userLogin.getId();
String password = userLogin.getPassword();
Map<String, String> result = new HashMap<String, String>();
result.put("result", "S");
result.put("message", "login success");
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(result);
}
}
This is an Alternative way with Jackson Library. I like #javaguy 's way, but using Jackson library could be more flexible so add this post.
Preparations
WebMvcConfigurerAdapter implements class or something equivalent with that
SpringFramework Environment. In my case, Eclipse Dynamic Web Project with Maven and spring-webmvc in pom.xml.
What I did...
Implement WebMvcConfigurerAdapter
Override Method configureMessageConverters
Change Controller parameters from HttpServeletRequest request, HttpServletResponse resp to #RequestBody Map<?, ?>.(You can change generic value. It does not matters for further process)
So Here's code.
ServerConfig.java (I block other Options to focus current issue)
#Configuration
#EnableWebMvc
#ComponentScan(basePackages={ ... }
, excludeFilters=#ComponentScan.Filter(Configuration.class))
//Filter 걸 때 Configuration.class 를 수동으로 등록해줘야 되는데 나은 방법 찾아보기
public class ServerConfig extends WebMvcConfigurerAdapter {
...
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new MappingJackson2HttpMessageConverter());
super.configureMessageConverters(converters);
}
};
And Controller (Change Parameter Types)
#Controller
#RequestMapping(value={"member"}, produces={"application/json"})
#ResponseStatus(value = HttpStatus.OK)
public class MemberApiController {
...
#RequestMapping(value={"/login"})
public #ResponseBody String login(#RequestBody Map<?, ?> jsonBody) throws JsonProcessingException {
System.out.println("Login request" + jsonBody.toString());
Map<String, String> result = new HashMap<String, String>();
String rs = "S";
String message = "SUCCESS";
System.out.println("ID >>> ", String.valueOf(jsonBody.get("id")));
System.out.println("PW >>> ", String.valueOf(jsonBody.get("password")));
result.put("result", rs);
result.put("result_msg", message);
mapper = new ObjectMapper();
return mapper.writeValueAsString(result);
}
};
However, since as far as I know #RequestBody does not have HttpSession, If you try to store data to HttpSession, you need another parameter HttpServletRequest.
I hope this could be a hand to others who has same problem with me :D
I'm trying to read a line of text from a URL and display the result in a Textview.
ISSUE/ERROR:
At present there is no error, the textview is not populated after I execute DownloadWebPage Async task.
INVESTIGATIONS
I believe I may not be calling this correctly, as I can't find any results from my debug calls, in DownloadWebPage. Also my URL has one line of code with two strings, if that makes any difference.
UPDATE:
In DownloadWebPage my logs commands are not showing in the log files - weird
CODE: ON CREATE:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.inbox_list);
textView = (TextView) findViewById(R.id.textView6);
// Hashmap for ListView
inboxList = new ArrayList<HashMap<String, String>>();
//ASYNC TASK I CREATED
new DownloadWebPageTask().execute();
// Another Async Task in my code
new LoadInbox().execute();
}
CODE: AsyncTask for Parsing Data from URL & Setting Data to Textview
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
System.out.println(response);
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
textView.setText(Html.fromHtml(result));
}
}
public void readWebpage(View view) {
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://www.url.com/blah.php" });
}
I am calling this method from JavaScript.
For the first time, it is giving null. But from the second time onwards, the data is coming.
Please help me.
#SuppressLint("JavascriptInterface")
public String loadClickedData() {
pDialog = ProgressDialog.show(this, "dialog title",
"dialog message", true);
new HttpAsyncTaskClickedData()
.execute("http://192.168.0.9/btrepo/btrepo/android_api.php");
return bdb.getmPosIdData();
}
Here we are getting data through AsyncTask in Android:
private class HttpAsyncTaskClickedData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("tag", "get_pos_details"));
nameValuePairs.add(new BasicNameValuePair("pos_id", posId));
return GET(urls[0], nameValuePairs);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
// Toast.makeText(getApplicationContext(), result+" in post ",
// Toast.LENGTH_LONG).show();
pDialog.dismiss();
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG)
.show();
bdb.setmPosIdData(result);
}
}
This method is for getting data from the server:
public static String GET(String url, List<NameValuePair> pair) {
InputStream inputStream = null;
String result = "";
try {
// create HttpClient
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(pair));
HttpResponse httpResponse = httpClient.execute(httpPost);
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
is = inputStream;
// convert inputstream to string
if (inputStream != null) {
// jObj = convertIsToJson(inputStream);
result = convertIsToJson(inputStream) + " ";
// jSonStr = result;
} else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
I am getting data from the server in json string format.
It is displaying attributes with null value like {pos["posid":null, "storeName":null]} etc..
In the following function
public String loadClickedData() {
pDialog = ProgressDialog.show(this, "dialog title",
"dialog message", true);
new HttpAsyncTaskClickedData()
.execute("http://192.168.0.9/btrepo/btrepo/android_api.php");
return bdb.getmPosIdData();
}
You execute your HttpAsyncTaskClickedData(), and return bdb.getmPosIdData() immediately. (Which will always be an issue for the 1st time)
The result of the AsyncTask is only available in onPostExecute, where you call bdb.setmPosIdData(result);.
#Override
protected void onPostExecute(String result) {
// ...
bdb.setmPosIdData(result); // result is only stored in bdb here!
}
The HttpAsyncTaskClickedData runs in the background, and possibly takes some time.
That is why your first call is always unable to get data, as you returned bdb.getmPosIdData() immediately after executing your AsyncTask.
private class HttpAsyncTaskClickedData extends
AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs
.add(new BasicNameValuePair("tag", "get_pos_details"));
nameValuePairs.add(new BasicNameValuePair("pos_id", posId));
return GET(urls[0], nameValuePairs);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
// Toast.makeText(getApplicationContext(), result+" in post ",
// Toast.LENGTH_LONG).show();
data = result;
pDialog.dismiss();
bdb.setmPosIdData(result);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = ProgressDialog.show(MainActivity.this, "dialog title",
"dialog message", true);
}
#SuppressLint("JavascriptInterface")
public String loadData() {
Toast.makeText(getApplicationContext(), data+ " hi ",
Toast.LENGTH_LONG).show();
return data;
}
}
and calling loadData() method from javascript.
This function is for get data by using post url in javascript
function jsonPost(){
var http = new XMLHttpRequest();
var url = "http://192.168.0.9/btrepo/btrepo/android_api.php";
var params = "tag=fav_stores&mobile=984989874";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
alert("hello "+http.send(params));
}
I have a Webpage loading into my WebView. This webpage loads a login page for the website. As the user enters his credentials he gets redirected to a certain page. I want to stop the loading of the webpage after user enters his credentials and get redirected to another activity instead of the default redirected page.
My idea of doing this is to catch the redirected url and compare it with the url created by me, if both match it should stop loading the default webpage and load another activity. However, Iam able to catch the redirected Urls and show them in a AlertDialog, but cannot stop the loading of the default web page.
Can anyone help me on this?
This is what I have tried:-
myWebView.loadUrl(url);
myWebView.setWebViewClient(new WebViewClient()
{
#Override
public void onPageFinished(WebView view, String url)
{
// TODO Auto-generated method stub
super.onPageFinished(view, url);
if(progressBar.isShowing())
{
progressBar.dismiss();
}
String absoluteUrl = view.getUrl();
absoluteUrl = Uri.decode(absoluteUrl);
//int absoulteCount = absoluteUrl.length();
String redirectedUrl = endpointHost+"Authorize/index"+myId;
//int redirectedCount = redirectedUrl.length();
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Details.this);
alertDialogBuilder.setNegativeButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int id)
{
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.setMessage(absoluteUrl);
alert.show();
if(absoluteUrl!=null && absoluteUrl.contains(redirectedUrl))
{
view.stopLoading();
Intent myIntent = new Intent(Details.this, Home.class);
startActivity(myIntent);
}
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
// TODO Auto-generated method stub
view.loadUrl(url);
HttpClient httpClient = new DefaultHttpClient();
URL myUrl;
URLConnection connection;
try
{
myUrl = new URL(url);
connection = myUrl.openConnection();
connection.setConnectTimeout(3000);
connection.connect();
int size = connection.getContentLength();
}
catch (Exception e) {}
String htmlContent = "";
HttpPost httpGet = new HttpPost(url);
HttpResponse response;
HttpContext httpContext = new BasicHttpContext();
try
{
response = httpClient.execute(httpGet);
if(response.getStatusLine().getStatusCode() == 200)
{
HttpEntity entity = response.getEntity();
if (entity != null)
{
InputStream inputStream = entity.getContent();
htmlContent = convertToString(inputStream);
}
}
}
catch (Exception e) {}
return true;
}
EDIT:- Suggested by #SimplePlan
myWebView.setWebViewClient(new WebViewClient()
{
#Override
public void onPageFinished(WebView view, String url)
{
// TODO Auto-generated method stub
super.onPageFinished(view, url);
if(progressBar.isShowing())
{
progressBar.dismiss();
}
}
private void showAlert2(String Url)
{
// TODO Auto-generated method stub
Url = Uri.decode(Url);
//int absoulteCount = absoluteUrl.length();
String redirectedUrl = endpointHost+"/AuthorizeDevice/index"+deviceId;
//int redirectedCount = redirectedUrl.length();
if(Url!=null && Url.contains("redirect_uri"+redirectedUrl+"?{StandardTokens}"))
{
myWebView.stopLoading();
Intent myIntent = new Intent(Details.this, Home.class);
startActivity(myIntent);
}else{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Details.this);
alertDialogBuilder.setNegativeButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int id)
{
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.setMessage(Url);
alert.show();
}
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
// TODO Auto-generated method stub
view.loadUrl(url);
showAlert2(url);
return true;
}
Try to implement like:
myWebView.setWebViewClient(new WebViewClient()
{
#Override
public void onPageFinished(WebView view, String url)
{
// TODO Auto-generated method stub
super.onPageFinished(view, url);
if(progressBar.isShowing())
{
progressBar.dismiss();
}
showAlert2(url);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
// TODO Auto-generated method stub
view.loadUrl(url);
HttpClient httpClient = new DefaultHttpClient();
URL myUrl;
URLConnection connection;
try
{
myUrl = new URL(url);
connection = myUrl.openConnection();
connection.setConnectTimeout(3000);
connection.connect();
int size = connection.getContentLength();
}
catch (Exception e) {}
String htmlContent = "";
HttpPost httpGet = new HttpPost(url);
HttpResponse response;
HttpContext httpContext = new BasicHttpContext();
try
{
response = httpClient.execute(httpGet);
if(response.getStatusLine().getStatusCode() == 200)
{
HttpEntity entity = response.getEntity();
if (entity != null)
{
InputStream inputStream = entity.getContent();
htmlContent = convertToString(inputStream);
}
}
}
catch (Exception e) {}
return true;
}
And showAlert2(url) method:
public void showAlert2(String Url) {
//String absoluteUrl = view.getUrl();
Url = Uri.decode(Url);
//int absoulteCount = absoluteUrl.length();
String redirectedUrl = endpointHost+"Authorize/index"+myId;
//int redirectedCount = redirectedUrl.length();
if(Url!=null && Url.contains(redirectedUrl))
{
myWebView.stopLoading();
Intent myIntent = new Intent(Details.this, Home.class);
startActivity(myIntent);
}else{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Details.this);
alertDialogBuilder.setNegativeButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int id)
{
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.setMessage(Url);
alert.show();
}
}
Try as per my answer and give me feedback on this