I am trying to accomplish something quite simple, yet I have found no good documentation on this. I have a webView, and I need to load a page in it that requires POST data. Seems like a simple process, yet I cannot find a way to display the result in a webView.
The process should be simple:
query(with POST data) -> webserver -> HTML response -> WebView.
I can submit data using a DefaultHttpClient, but this cannot be displayed in a WebView.
Any suggestions?
Much Thanks
Solution
private static final String URL_STRING = "http://www.yoursite.com/postreceiver";
public void postData() throws IOException, ClientProtocolException {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("foo", "12345"));
nameValuePairs.add(new BasicNameValuePair("bar", "23456"));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL_STRING);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String data = new BasicResponseHandler().handleResponse(response);
mWebView.loadData(data, "text/html", "utf-8");
}
Two ways to load post response in webview:
webview.loadData(): Like what you have posted in your solution. But "content loaded through this mechanism does not have the ability to load content from the network".
webview.postUrl(): Use this if post response needs to load content from the network. (NOTE: only accessible from api-level 5, which means no android 1.6 or lower)
String postData = "username=my_username&password=my_password";
webview.postUrl(url,EncodingUtils.getBytes(postData, "BASE64"));
(source: http://www.anddev.org/other-coding-problems-f5/webview-posturl-postdata-t14239.html)
Try this:
private static final String URL_STRING = "http://www.yoursite.com/postreceiver";
public void postData() throws IOException, ClientProtocolException {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("foo", "12345"));
nameValuePairs.add(new BasicNameValuePair("bar", "23456"));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL_STRING);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
}
I would recommend doing this as part of an AsyncTask and updating the WebView afterwards
I use webView.loadData() to do client post, and it will display content of url, my code :
public static void webview_ClientPost(WebView webView, String url, Collection< Map.Entry<String, String>> postData){
StringBuilder sb = new StringBuilder();
sb.append("<html><head></head>");
sb.append("<body onload='form1.submit()'>");
sb.append(String.format("<form id='form1' action='%s' method='%s'>", url, "post"));
for (Map.Entry<String, String> item : postData) {
sb.append(String.format("<input name='%s' type='hidden' value='%s' />", item.getKey(), item.getValue()));
}
sb.append("</form></body></html>");
webView.loadData(sb.toString(), "text/html", "UTF-8");
}
use function webview_ClientPost() :
Map<String, String> mapParams = new HashMap<String, String>();
mapParams.put("param1", "111");
mapParams.put("param2", "222");
Collection<Map.Entry<String, String>> postData = mapParams.entrySet();
webview_ClientPost(webView1, "http://www.yoursite.com/postreceiver", postData);
If you use a WebView from the start could it work?
A Webview with a html/js that does the POST, and naturally displays the result.
You can also pass post key:value pair in JSON format to web view.
String userName = "admin";
String password = "Admin#2021";
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("userName", userName);
jsonObject.put("password", password);
} catch (JSONException e) {
e.printStackTrace();
}
String url = "http://www.example.com";
webView.postUrl(url, jsonObject.toString().getBytes());
Related
I am trying make a call to a Web Service (asmx) with parameters but I keep getting a "Missing parameter: Lane" response. the code below is what i am using
final HttpClient Client = new DefaultHttpClient();
String jsonstring = "", step = "0";
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Lane", "1"));
params.add(new BasicNameValuePair("Name", "Test test"));
HttpPost httppostreq = new HttpPost(url);
httppostreq.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpresponse = Client.execute(httppostreq);
jsonstring = EntityUtils.toString(httpresponse.getEntity());
I am able to call the Web Serviceusing Postman when I add the parameters in the header and set the "Content Type:application/x-www-form-urlencoded" but can't make it work in Android Studio
This is the code in my webservice:
[WebMethod]
public void MyTestService(string Lane, string Name)
{
Dictionary<string, object> parameter = new Dictionary<string, object>();
parameter.Add("#lane", Lane);
parameter.Add("#name", Name);
DataSet dt = DataAccess.executeStoreProcedureDataSet("sp_GetLaneName", parameter);
string jsonReturned = JsonConvert.SerializeObject(dt, Formatting.Indented);
Context.Response.ContentType = "text/plain; charset=UTF-8";
Context.Response.Write(jsonReturned);
}
Add Header to your request below
httppostreq.setHeader(HTTP.CONTENT_TYPE,
"application/x-www-form-urlencoded;charset=UTF-8");
I am working on REST API with "POST" type, I want to consume it by using WebView. I am using webView.postUrl() but I also need authentication header with my POST request which I am not able to do.
My code is given below, along with the information needed for my Rest api with POST type. Kindly guide me to solve this problem.
// Here is my block of code for using POST type Rest API
private static final String URL_STRING = "https://derxxxlist.net/uxxxco/Surxxxe/Membxxxhip/Axxxxin";
public void postData(WebView mWebView) throws IOException, ClientProtocolException {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("Username", "xxx#aaa.com"));
nameValuePairs.add(new BasicNameValuePair("Password", "qwerasdf"));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL_STRING);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String data = new BasicResponseHandler().handleResponse(response);
mWebView.loadData(data, "text/html", "utf-8");
}
// Here I am passing my webView in my above method:
new Thread(new Runnable() {
#Override
public void run() {
try {
postData(webView);
} catch (Exception e) {
e.printStackTrace();
}
}}).start();
What I want is to pass authentication header along with my above post API.
// My Authentication header
"authorization", "amx A93reRTUJHsxxxxxxxxxxCgps102ciuabc="
You can set the header of the Http request using setHeader
httppost.setHeader("Authorization", "amx A93reRTUJHsxxxxxxxxxxCgps102ciuabc=");
A friend have a Rest API with Django, and Im trying to make and android app for it, but I having problems with the authentication.
First i get the CSRF token, just making a get call and taking the value.
public String getCFSRToken() throws Exception{
String csrftokenValue="";
httpClient.execute(new HttpGet(urlBasic));
cookieStore = httpClient.getCookieStore();
List <Cookie> cookies = cookieStore.getCookies();
for (Cookie cookie: cookies) {
Log.v("csrftoken",cookie.getName());
if ( cookie.getName().compareTo("csrftoken")==0) {
csrftokenValue = cookie.getValue();
}
}
return csrftokenValue;
}
Then I try to make the authentication:
public void login3() throws Exception{
String urlLogin ="/login";
String url = urlBasic+urlLogin;
String username = "jesus.m.martinez.garcia";
String password = "lolofree";
String userpass = username +":"+password;
HttpPost post = new HttpPost(url);
// List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
// nameValuePairs.add(new BasicNameValuePair("username", username));
// nameValuePairs.add(new BasicNameValuePair("password", password));
// post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
String basicAuth = "Basic " + new String(Base64.encode(userpass.getBytes(),Base64.NO_WRAP ));
post.addHeader("Authorization", basicAuth);
post.addHeader("X-CSRFToken", getCFSRToken());
HttpResponse response = httpClient.execute(post);
CookieStore as = httpClient.getCookieStore();
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
String pagina="";
while ((line = rd.readLine()) != null) {
pagina= pagina + "\n"+line;
}
System.out.println(pagina);
}
If I don't add the CSRF header I receive always a 403 Forbidden, so I suppose that part is correct, but when I try to do the login with the post (as you can see I have try without codification and basic), I always receive a 200 Ok, but I receive an HTML page for logging and I don't get the session cookie, that's what is killing me.
I asked my friend and he told me, he didn't modify the authentication of Django framework, so I suppose is not digest. Any idea what I am doing wrong?
Thank you in advance ;)
I have a code written in python which send's in the viewstate and the formvalues in this way
send('_VIEWSTATE=%2FwEPDwULLTE0MDM4Mz.........%2BhFiTeLDMyk...................&_EVENTVALIDATION=%2FwEWA....I%2.................mtK6HmOBny%2............NHcX5PO4r9oSpA&TextBox1='+payload+'&Button1=click\r\n')
where the dots stand for the rest of the string. Now i want to send this by httppost from android. I'm not able to understand how to translate the above code to httppost, i tried making the __VIEWSTATE,__EVENTVALIDATION as key's and the string's as value but that did not work. How can i send it ?? how do i send the above string as it is via httppost.
Do this:
private static final String DATA = "_VIEWSTATE=%2FwEPDwULLTE0MDM4Mz.........";
public String send() {
String result = null;
try {
HttpPost request = new HttpPost(new URI("<your POST uri>"));
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("data", DATA));
request.setEntity(new UrlEncodedFormEntity(params));
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(request);
BasicResponseHandler handler = new BasicResponseHandler();
result = handler.handleResponse(response);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
Call the send() method from a background Thread.
I have an example json as below:
{
"Passwd":"String content",
"Userme":"String content"
}
how to construct the JSON String as above and give it as argument to HttpPost in Android.?
Can anyone help me in sorting out this issue.
thanks in Advance,
You can make use of JSONObject to create a simple json like { "Passwd":"String content", "Userme":"String content" } try something like this.
String json="";
JSONObject jobj = new JSONObject();
jobj.put("Userme", "Username");
jobj.put("Passwd", "PasswordValue");
json = jobj.toString();
Above String can be sent as one of the parameter using HTTP POST easily. Below function takes url and json as parameters to make POST request.
private void httpPost(String json,String url) throws ClientProtocolException, IOException{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("json", json));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
httpClient.execute(httpPost);
}