I'm trying to use httpost to get data from our WCF webservice
If the webservice function is without params , something like List getAllMessages()
I'm getting the List in json, no problem here
The tricky part is when the function needs to get argument
let's say Message getMessage(string id)
when trying to call this kind of functions I get error code 500
The working code is:
public String GetAllTitles()
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://www.xxx.com/Service/VsService.svc/GetAllTitles");
httppost.setHeader("Content-Type", "application/json; charset=utf-8");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
return readHttpResponse(response);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
this code works great for functios without arguments..
I took this code and changed it to:
public String SearchTitle(final String id)
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://www.xxx.com/Service/VsService.svc/SearchTitle");
httppost.setHeader("Content-Type", "application/json; charset=utf-8");
httppost.setHeader("Accept", "application/json; charset=utf-8");
NameValuePair data = new BasicNameValuePair("id",id);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(data);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
return readHttpResponse(response);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
The function header in thr webservice is:
[OperationContract]
public TitleResult SearchTitle(string id)
{
Stopwatch sw = LogHelper.StopwatchInit();
try
{
TitleManager tm = new TitleManager();
Title title = tm.TitleById(id);
sw.StopAndLog("SearchTitle", "id: " + id);
return new TitleResult() { Title = title };
}
catch (Exception ex)
{
sw.StopAndLogException("SearchTitle", ex, "id: " + id);
return new TitleResult() { Message = ex.Message };
}
}
Anyone can see what am I missing?
Thanks, I'm breaking my head over this one.
List isn't json,
try
String data = "{ id : \"" + id + "\" }";
Don't forget to set Content-Length to data.length.
Related
i am new to android and i am working on one application ,In which i have to add books by posting all book details to pHp server,here i am using httpPost call to send all book details,but in pHp server there is a line,
$this->get('security.context')->getToken()->getUser()
i cannot able to call it simply by httpPost in android..so i really need help to solve this problem..so please help me how to call it in android..thanks in advance....
this is the httppost used to send book details..
HttpClient httpClient = new DefaultHttpClient();
// replace with your url
HttpPost httpPost = new HttpPost("www.example.com");
//Post Data
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(3);
nameValuePair.add(new BasicNameValuePair("book", "name"));
nameValuePair.add(new BasicNameValuePair("price", "rate"));
nameValuePair.add(new BasicNameValuePair("author","author"));
//Encoding POST data
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch (UnsupportedEncodingException e) {
// log exception
e.printStackTrace();
}
//making POST request.
try {
HttpResponse response = httpClient.execute(httpPost);
// write response to log
Log.d("Http Post Response:", response.toString());
} catch (ClientProtocolException e) {
// Log exception
e.printStackTrace();
} catch (IOException e) {
// Log exception
e.printStackTrace();
}
}
this is the php post function
public function handlePOST($params, Request $request) {
$book = new Book();
if (isset($params['isbn'])) {
$book->setIsbn($params['isbn']);
}
$book->setTitle($params['title']);
if (isset($params['type'])) {
$book->setFrequency($params['type']);
}
if (isset($params['period'])) {
$book->setPeriod($params['period']);
}
if (isset($params['frequency'])) {
$book->setFrequency($params['frequency']);
}
if (isset($params['type'])) {
$book->setType($params['type']);
}
if (isset($params['author'])) {
$book->setAuthor($params['author']);
}
if (isset($params['lang'])) {
$book->setLang($params['lang']);
}
if (isset($params['pages'])) {
$book->setPages($params['pages']);
}
if (isset($params['price'])) {
$book->setPrice($params['price']);
}
if (isset($params['status'])) {
$book->setStatus($params['status']);
} else {
$book->setStatus(1);
}
if (isset($params['bookCondition'])) {
$book->setBookCondition($params['bookCondition']);
}
//$book->setAvailableFor($params['availableFor']);
if (isset($params['description'])) {
$book->setDescription($params['description']);
}
if (isset($params['genre'])) {
$book->setGenre(json_encode($params['genre']));
}
// $repository = $this->getDoctrine()->getRepository('UserBundle:User');
// $user = $repository->findOneBy(
// array('id' =>$params['userid'])
// );
//how to call below code
$user = $this->get('security.context')->getToken()->getUser();
$user->setRewardPoints($user->getRewardPoints() + 10);
$book->setCreatedBy($user->getId());
$em = $this->getDoctrine()->getEntityManager();
$em->persist($book);
$em->flush();
// $this->triggerBookChange($book->getTitle(), $params['type']);
$response = new Response(json_encode($params));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
I'm making a google login through GoogleTransport and ClientLogin.
private final GoogleTransport transport = new GoogleTransport();
private final ClientLogin authenticator = new ClientLogin();
Then I'm accessing the Picasa web api.
transport.setVersionHeader(PicasaWebAlbums.VERSION);
transport.applicationName = "google-picasaandroidsample-1.0";
HttpTransport.setLowLevelHttpTransport(ApacheHttpTransport.INSTANCE);
authenticator.authTokenType = PicasaWebAlbums.AUTH_TOKEN_TYPE;
authenticator.username = StaticVariables.USER_NAME+StaticVariables.USER_DOMAIN;
authenticator.password = StaticVariables.USER_PASSWORD;
try {
authenticator.authenticate().setAuthorizationHeader(transport);
HttpRequest request = transport.buildPostRequest();
request.setUrl("https://picasaweb.google.com/data/feed/api/user/default");
request.execute();
} catch (HttpResponseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The above is working fine.
Now I want to set a POST request. But buildPostRequest() method does not support any String parameter. So, unable to post any data at the URL. How to achieve it? Please help.
You may use HttpPost with NameValuePair
private boolean sendData(ArrayList<NameValuePair> data) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(YOUR_URL);
httppost.setEntity(new UrlEncodedFormEntity(data));
HttpResponse response = httpclient.execute(httppost);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
Then create your Name Value pairs in a different method as
private ArrayList<NameValuePair> setupData() {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
3);
nameValuePairs.add(new BasicNameValuePair(USERID, SAMPLE_USER_ID);
nameValuePairs.add(new BasicNameValuePair(USERNAME, SAMPLE_USER_NAME));
return nameValuePairs;
}
Atlast call the send data method in an AsyncTask or Intent service as sendData(setupdata())
Data in a post request is usually sent in the body of the request.
I have an application in Android, in which I were reading files from the remote server, code for reading file is given below;
URI uri = null;
try {
uri = new URI("http://192.168.1.116/Server1/Users.xml");
} catch (URISyntaxException e) {
e.printStackTrace();
}
HttpGet httpget = new HttpGet(uri);
httpget.setHeader("Content-type", "application/json; charset=utf-8");
httpget.setHeader("host", "192.168.1.116");
HttpResponse response = null;
try {
response = httpClient.execute(httpget);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
HttpEntity responseEntity = response.getEntity();
String result = null;
try {
result = EntityUtils.toString(responseEntity);
Log.d("SERVER1", result);
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Now all the remote files are behind proxy (Microsoft ISA Server) which required authentication to access the files. Please guide me how I can pass authentication parameters from android to access the files.
I have tried the following codes but useless,
URL uri = null;
try {
uri = new URI("http:// 192.168.1.116/CookieAuth.dll?Logon");
} catch (URISyntaxException e) {
e.printStackTrace();
}
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider()
.setCredentials(
AuthScope.ANY,
new NTCredentials(username, password, deviceIP,
domainName));
HttpPost httppost = new HttpPost(uri);
httppost.setHeader("Content-type",
"application/x-www-form-urlencoded");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("curl", "Z2FServer1/users.xmlZ2F"));
params.add(new BasicNameValuePair("formdir", "3"));
params.add(new BasicNameValuePair("username", "test"));
params.add(new BasicNameValuePair("password", "test"));
UrlEncodedFormEntity ent = null;
try {
ent = new UrlEncodedFormEntity(params, HTTP.UTF_8);
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
httppost.setEntity(ent);
try {
response = httpclient.execute(httppost);
Log.i("Test", response.getStatusLine().toString());
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
result = convertStreamToString(instream);
Log.d("ISA Server", result);
instream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
But it’s giving HTTP1.1 500 Internal Server Error. I have also tried following link but same error
https://stackoverflow.com/a/10937857/67381
In my case i use
public static DefaultHttpClient getClient(String username, String password,
Integer timeOut) {
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, timeOut);
HttpConnectionParams.setSoTimeout(httpParams, timeOut);
DefaultHttpClient retHttpClient = new DefaultHttpClient(httpParams);
if (username != null) {
retHttpClient.getCredentialsProvider().setCredentials(
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
new UsernamePasswordCredentials(username, password));
}
return retHttpClient;
}
Try, may be works.
P.S.
It's not for ISA, for MS C# WebService Application, but maybe...
I want my application to send two strings through the query string to a php file that will handle them as POST variables.
So far I have this code
public void postData() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("www.mywebsite.com/my_phpfile.php?var1=20&var2=31");
try {
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
I think it's an easy problem to solve but it's my first android app and I'd appreciate all the help.
Use nameValuePairs to pass data in the POST request.
Try it like this :
public void postData() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/yourscript.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "123"));
nameValuePairs.add(new BasicNameValuePair("string", "Hey"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// Catch Protocol Exception
} catch (IOException e) {
// Catch IOException
}
}
I'm creating an application for our Android devices. The aim of this section is to post a username and password (currently just assigned as a string) to a web service and to receive a login token. When running the code, at the getOutputStream() line, my code terminates and will no progress any further.
I have assigned the android emulator GSM access and also set the proxy and DNS server within Eclipse. I'm not sure where to go with it now!
This is within my onHandleIntent():
protected void onHandleIntent(Intent i) {
try{
HttpURLConnection http_conn = (HttpURLConnection) new URL("http://www.XXXXX.com").openConnection();
http_conn.setRequestMethod("POST");
http_conn.setDoInput(true);
http_conn.setDoOutput(true);
http_conn.setRequestProperty("Content-type", "application/json; charset=utf-8");
String login = URLEncoder.encode("XXXXX", "UTF-8") + "=" + URLEncoder.encode("XX", "UTF-8");
login += "&" + URLEncoder.encode("XXXXX", "UTF-8") + "=" + URLEncoder.encode("XX", "UTF-8");
OutputStreamWriter wr = new OutputStreamWriter(http_conn.getOutputStream());
//TERMINATES HERE
wr.write(login);
wr.flush();
BufferedReader rd = new BufferedReader(new InputStreamReader(http_conn.getInputStream()));
String line = rd.toString();
wr.close();
rd.close();
http_conn.disconnect();
}
catch (IOException e){
}
}
This is my first go at java and have only been writing it for a few days so bear with me if I've missed something obvious.
Thanks
If you want to POST something using HTTP, why not use HTTP POST? ;-)
Here is an example snippet:
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
Source: http://www.androidsnippets.com/executing-a-http-post-request-with-httpclient
This may not be the appropriate answer, but will certainly be helpful to you. I have used this code for sending and receiving the request and reply resp, to a webservice.
This code is working, but will need some Refactoring, as i have used some extra variable, which are not needed.
I have used the NameValuePair here for Post
public String postData(String url, String xmlQuery) {
final String urlStr = url;
final String xmlStr = xmlQuery;
final StringBuilder sb = new StringBuilder();
Thread t1 = new Thread(new Runnable() {
public void run() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urlStr);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
1);
nameValuePairs.add(new BasicNameValuePair("xml", xmlStr));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
Log.d("Vivek", response.toString());
HttpEntity entity = response.getEntity();
InputStream i = entity.getContent();
Log.d("Vivek", i.toString());
InputStreamReader isr = new InputStreamReader(i);
BufferedReader br = new BufferedReader(isr);
String s = null;
while ((s = br.readLine()) != null) {
Log.d("YumZing", s);
sb.append(s);
}
Log.d("Check Now",sb+"");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} /*
* catch (ParserConfigurationException e) { // TODO
* Auto-generated catch block e.printStackTrace(); } catch
* (SAXException e) { // TODO Auto-generated catch block
* e.printStackTrace(); }
*/
}
});
t1.start();
try {
t1.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Getting from Post Data Method "+sb.toString());
return sb.toString();
}
String line = rd.toString();
should be
String line = rd.readLine();
that might do the trick. rd.toString() gives you a String representation of your BufferedReader. It does not trigger the HTTP operation. I did not test your code, so there might be other errors as well, this was just the obvious one.