Android Studio Missing parameter error when calling POST with parameters - android

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");

Related

Cant send json to server

I'm trying to send a json file to remote server. If I try it, using this site:
https://www.hurl.it/ passing a json like this:
it works. But If I try it from my code, I have some trouble.
ArrayList<NameValuePair> nameValuePairs1 = new ArrayList<NameValuePair>();
JSONArray list1 = new JSONArray();
list1.add("12345678");
Map obj=new LinkedHashMap();
obj.put("company_id","1");
obj.put("phones", list1);
obj.put("name","Alexy");
obj.put("birthdate","12.03.2014");
obj.put("email","nesalexy#mail.ru");
nameValuePairs1.add(new BasicNameValuePair("json", obj.toString()));
try {
URL url = new URL("http://crm.pavlun.info/api/register");
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url.toURI());
httpPost.setEntity(new StringEntity(nameValuePairs1.toString(), "UTF-8"));
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept-Encoding", "application/json");
HttpResponse response = httpClient.execute(httpPost);
Log.e("r ", response.toString());
}catch(Exception e) {
e.printStackTrace();
}
This is my json example: I need to create something like this: "json":{"company_id":"1","phones":["555555"],"photo":"/files/clients_photos/tmp/484629825.JPG","name":"sdfsdfdsf","birthdate":"10.02.2014", "email":"sdf#sdf.ff"}
UPD:
I have the following error:
{"status":"error","message":"Customer data is empty!"}
Maybe something is wrong in my json.
UDP:
working code
ArrayList<NameValuePair> nameValuePairs1 = new ArrayList<NameValuePair>();
JSONObject joB = new JSONObject();
JSONArray list1 = new JSONArray();
list1.add("258963147");
Map obj=new LinkedHashMap();
obj.put("company_id","1");
obj.put("phones", list1);
obj.put("name","Alexy");
obj.put("birthdate","12.03.2014");
obj.put("email","nesalexy#mail.ru");
org.json.JSONObject jsonqwe;
try {
JSONParser operationLink = new JSONParser();
ArrayList<NameValuePair> postP = new ArrayList<NameValuePair>();
postP.add(new BasicNameValuePair("json", JSONValue.toJSONString(obj)));
jsonqwe = operationLink.makeHttpRequest("http://crm.pavlun.info/api/register", "POST", postP);
Log.e("sad", jsonqwe.toString());
}catch(Exception e) {
e.printStackTrace();
}
You're problem is that you're not building a JSON object, but using the map's toString() method, which won't give you a properly formatted JSON object.
Try JSONObject's constructor that takes a map as parameter. And than call toString() on the JSONObject.
Try yo change
Map obj=new LinkedHashMap();
to
JSONObject obj=new JSONObject();
you need to send a JSON value
A more suitable solution would be to build a JSONObject instead of the Map you're using. Something like this:
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
JSONArray phoneNumbers = new JSONArray();
phoneNumbers.add("12345678");
JSONObject obj=new JSONObject();
obj.put("company_id","1");
obj.put("phones", phoneNumbers);
obj.put("name","Alexy");
obj.put("birthdate","12.03.2014");
obj.put("email","nesalexy#mail.ru");
nameValuePairs.add(new BasicNameValuePair("json", obj.toString()));
try {
URL url = new URL("http://crm.pavlun.info/api/register");
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url.toURI());
httpPost.setEntity(new StringEntity(nameValuePairs.toString(), "UTF-8"));
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept-Encoding", "application/json");
HttpResponse response = httpClient.execute(httpPost);
Log.e("r ", response.toString());
}catch(Exception e) {
e.printStackTrace();
}
This line will return garbage (as far server is concerned)
nameValuePairs1.toString()
because an ArrayList does implement toString like you are expecting. You should be using JSONArray/JSONObject instead.
In the hurl site example one name valu pair is sent. To send name value pais your content type should be form url encoded. So change:
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept-Encoding", "application/json");
to
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
Maybe this will help:
httpPost.setHeader("ENCTYPE","multipart/form-data");
EDIT:
As others already stated do not use a Map but a JSONObject. Then change
httpPost.setEntity(new StringEntity(nameValuePairs1.toString()));
to:
String nameValuPairsText = nameValuePairs.toString();
nameValuPairsText = nameValuPairsText.substring(1, nameValuPairsText.length()-1);
httpPost.setEntity(new StringEntity(nameValuPairsText, "UTF-8"));

how to post json format data to server

How to post JSON data to .net server?
can i use:
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(URL);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("Code", Code));
pairs.add(new BasicNameValuePair("Subject", Subject));
httpPost.setEntity(new UrlEncodedFormEntity(pairs));
httpResponse=httpClient.execute(httpPost);
or any other format to send json data?
You can create JSON Object and Put data into that object and pass it to the server..
use,
JSONObject json = new JSONObject();
json.put("UserName", "test2");
json.put("FullName", "1234567");
to put data into json object...
use
json.toString(); to send the data and
request.setHeader(HTTP.CONTENT_TYPE, "application/json");
to mark the json format...
Refer these links for more:
Send and Receive Json android-php
Sending json from Android
Here is the solution after referring many sources...
protected Void doInBackground(Void... params) {
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(URL);
httpPost.setHeader("Content-Type", "application/json");
JSONObject jsonObject = new JSONObject();
jsonObject.put("Code", Code);
jsonObject.put("Subject", Subject);
stringEntity = new StringEntity(jsonObject.toString());
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
httpResponse=httpClient.execute(httpPost);
return null;
}
protected void onPostExecute(Void result) {
//to see the response
httpEntity=httpResponse.getEntity();
Response=EntityUtils.toString(httpEntity);
System.out.println("Response "+Response);
int Response_Code = httpResponse.getStatusLine().getStatusCode();
System.out.println("Response_Code "+Response_Code);
}
Thanks for your response, also helped me find this.
You can add one more parameter to the URL named json(or any name you want), and use the json string as value and then get the json in your php.
example:
pairs.add(new BasicNameValuePair("Code", Code));
pairs.add(new BasicNameValuePair("Subject", Subject));
pairs.add(new BasicNameValuePair("Json", my_jsons_tring));

How to POST key/value pairs instead of a JSON Object using Spring for Android?

I am trying to use Spring for Android to do a standard HTTP POST to a url where the body of is just a list of parameters (like key-value pairs) and not a JSON object.
I would like the response to be converted from JSON to the Java ResponseObject, but from what I can tell, Spring is also converting my body into JSON as well.
Here is my code:
Map<String, Object> params = new HashMap<String, Object>();
params.put("client_id", mClientId);
params.put("state", mState);
params.put("username", mUsername);
params.put("password", mPassword);
return getRestTemplate().postForObject(url, params, ResponseObject.class);
Thank you in advance!
Try this
posting simple name value pair list
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
try{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("name", nameString));
nameValuePairs.add(new BasicNameValuePair("Country", "country name"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
}catch (ClientProtocolException e) {
// TODO Auto-generated catch block
}
Use .exchange()
// Create the request body as a MultiValueMap
MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();
body.add("client_id", mClientId); // and so on
// Note the body object as first parameter!
HttpEntity<?> httpEntity = new HttpEntity<Object>(body, requestHeaders);
MyModel model = restTemplate.exchange("/api/url", HttpMethod.POST, httpEntity, MyModel.class);

how to post data using JSON for httpPost in Android

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);
}

Android Webview POST

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());

Categories

Resources