I need to get the Contacts of GAL from exchange server..
I have a method that searches the GAL on the Exchange server
for that there is
query string : The name to search the GAL for....
the code is given as follows....
public int searchGAL(
String query,
StringBuffer result) throws Exception
{
// Create the request
String uri = mUri + "Search";
String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
+ "<Search xmlns=\"Search:\">\n" +
"\t<Store>\n"
+ "\t\t<Name>GAL</Name>\n"
+ "\t\t<Query>" + query + "</Query>\n"
+ "\t\t<Options>\n"
+ "\t\t\t<Range>0-99</Range>\n"
+ "\t\t</Options>\n"
+ "\t</Store>\n"
+ "</Search>";
// Send it to the server
HttpResponse response = sendPostRequest(createHttpPost(uri,xml,true));
// Check the response code to see if the result was 200
// Only then try to decode the content
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode == 200)
{
// Decode the XML content
result.append(decodeContent(response.getEntity()));
}
// parse and return the results
return statusCode;
}
How to get the the all contacts in the server,.. how to query that ??
when i give space.. the query will search the names starting with space.. but i need to return all contacts when i pass space as query string.
http://msdn.microsoft.com/en-us/library/ff631384(v=exchg.80).aspx
Related
I'm trying to upload some photos taken by an application in a distant database. To be clear :
I take a piture from my app
I send if to a web service (witten in .net, svc file)
The WS upload it in the database
The way i'm doing it : i'm sending the byte[] recovered from the picture that way
String url = MyAddress + "insert_img?login='"
+ login_result + "'&epc='" + code + "'&title='" + t
+ "'&image='" + base64EncodedString + "'&descrip='" + d
+ "'";
BufferedReader inStream = null;
System.out.println(url);
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpR = new HttpGet(url);
httpR.setHeader("Accept", "application/json");
httpR.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(httpR);
My problem is that I have to compress A LOT the picture in order it to be send. The picture, or base64EncodedString field, is created like that :
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
mImageView.setImageDrawable(null);
mImageView.setImageBitmap(thumbnail);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 1, baos);
byte[] outputByteArray = baos.toByteArray();
base64EncodedString = Base64.encodeToString(outputByteArray, Base64.NO_WRAP + Base64.URL_SAFE);
As you can see, the image is very very very compressed, and when I recover it it's more or less a 4-colors stamp. And if I do not compress it a lot, image is not inserted.
So first of all : Am I doing it the right way to deal ? And also, why is there no insertion when the picture is too big and how, if possible, to track the error ?
Thanks !
EDIT :
I've modified my code that way, server side :
public string insert_report(Stream stream)
{
string login = "";
string epc = "";
string title = "";
string image = "";
string descrip = "";
MultipartParser parser = new MultipartParser(stream);
Entities entities = new Entities();
string res = "";
if (parser != null && parser.Success)
{
res += parser.Filename;
foreach (var content in parser.MyContents)
{
string name = content.PropertyName;
string str = Encoding.UTF8.GetString(content.Data);
res += "name : " + name +"---";
res += "content : " + str+"---";
if (name.Contains("login"))
{
login = str;
}
if (name.Contains("epc"))
{
epc = str;
}
if (name.Contains("title"))
{
title = str;
}
if (name.Contains("image"))
{
image = str;
}
if (name.Contains("descrip"))
{
descrip = str;
}
}
}
res+= " res returned by server : "+ entities.insert_report(login, epc, title, image, descrip);
entities.SaveChanges();
return res;
}
But there are some problems : the insert_report function return -1... How do I recover the error given by that function ?
Do you receive 414 (Request-URI Too Long) error? You should use HTTP POST method to upload your images as POST body - no Base64 encoding will be also required. Look at https://stackoverflow.com/a/7632849/2714032
I currently have a mediaplayer and am trying to get the redirect address from my source path. Since the media player does not support redirect handling, I am trying to get the redirected url path by creating a httpurlconnection etc. However, I'm not sure if I am doing it right. Any help would be appreciated. Thanks.
Code:
Log.d(TAG, "create url - test");
URL testUrl = new URL(path);
HttpURLConnection conn = (HttpURLConnection)testUrl.openConnection();
String test = conn.getURL().toString();
String test1 = conn.getHeaderField(2);
String test2 = conn.toString();
Log.d(TAG, "normal stuff test is: " + test);
Log.d(TAG, "header field test is: " + test1);
Log.d(TAG, "url to string is: " + test2);
The code below follows one hop of URL redirects. By using a HTTP HEAD request rather than GET it consumes radically less bandwith. It should be fairly straight forward to extend this method to handle multiple hops.
public URI followRedirects(URI original) throws ClientProtocolException, IOException, URISyntaxException
{
HttpHead headRequest = new HttpHead(original);
HttpResponse response = client.execute(headRequest);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY ||
statusCode == HttpStatus.SC_MOVED_TEMPORARILY)
{
String location = response.getHeaders("Location")[0].toString();
String redirecturl = location.replace("Location: ", "");
return new URI(redirecturl);
}
return original;
}
It assumes you have already set up an HttpClient stored in the field client.
Also see this question.
I am developing a final year project where I need to connect Android emulator with MySQL database in order to retrieve values. Java file:
public class connectivity extends Activity {
/** Called when the activity is first created. */
TextView txt;
public static final String KEY_121 = "http://10.0.2.2/mysqlcon.php";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout rootLayout = new LinearLayout(getApplicationContext());
txt = new TextView(getApplicationContext());
rootLayout.addView(txt);
setContentView(rootLayout);
// Set the text and call the connect function.
txt.setText("Connecting...");
// call the method to run the data retreival
txt.setText(getServerData(KEY_121));
}
private String getServerData(String returnString) {
InputStream is = null;
String result = null;
// the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("year", "1970"));
// http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(KEY_121);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// parse json data
try {
JSONArray jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
Log.i("log_tag", "id: " + json_data.getInt("id") + ", name: " + json_data.getString("name") + ", sex: " + json_data.getInt("sex") + ", birthyear: " + json_data.getInt("birthyear"));
// Get an output to the screen
returnString += "\n\t" + jArray.getJSONObject(i);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return returnString;
}
}
I have also given an internet permission in my Android manifest file. But after running the application I get the following error in logcat:
ERROR PARSING DATA org.json.JSONException:A JSONArraytext must start with '[' at character 0
I think this goes to show that a null value is being returned. Please help me out as this is my final year project. I have spent hours trying to find the solutions but it has been of no use.
I am currently using Android 2.2. The wamp server is on the localhost so I am using the address 10.0.2.2 which is a special alias to localhost (127.0.0.1). Any help will be really appreciated.
Here is the PHP code:
<?php
mysql_connect("127.0.0.1","root","chetan");
mysql_select_db("db1");
$q=mysql_query("SELECT * FROM people WHERE birthyear>'".$_REQUEST['year']."'");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output,JSON_FORCE_OBJECT));
mysql_close();
This is actually an issue I've run into before. The problem is your server isn't outputting valid JSON. It's missing some of the markup. I suggest you print the raw text of the response to Logcat and examine it. Perhaps even pass it into a JSON validator. That will also help you figure out if it is returning an empty value. If it's returning an empty value, then you'll need to debug your server...not your client...
Additionally, try visiting the php page from your browser and letting it simply display the JSON response. This will allow you to see what's being written by the server and help you determine where the problem really is. Just be aware, because the server is expecting a POST the easiest way to test this would probably to be to create a simple html form to POST the test data to that page. Without doing that, getting a browser to do a POST on it's own can be a pain.
do u need to use connection to php??? if not you can directly connect to mysql db to retrieve the result:
// Assume function to be :
public String customerData() {
String customerInfo = ""; //To store result
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection(
"jdbc:mysql://10.0.2.2:3306/retailer","root","pswrd");
PreparedStatement statement = con.prepareStatement("SELECT * FROM customers");
ResultSet result = statement.executeQuery();
while(result.next()) {
customerInfo = customerInfo + result.getString("name") + "&" +
result.getString("C_ID") + "&" + result.getString("address") +
"&" + result.getString("email");
// Here "&"s are added to the return string. This is help to split the
// string in Android application
}
} catch(Exception exc) {
System.out.println(exc.getMessage());
}
return customerInfo;
}
But to your project library include Connector jar file for Mysql.
I have a rest webservice that takes a POST metod with multipart message:
#Path("transferFile")
#POST
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces(MediaType.APPLICATION_XML)
public String multipartTest(com.sun.jersey.multipart.MultiPart data) {
try {
// get first body part (index 0)
BodyPart bp = multiPart.getBodyParts().get(0);
etc..
Now I am trying to write a java client for that. I started with a simple jersey client:
view plaincopy to clipboardprint?
MultiPart multiPart = new MultiPart();
multiPart.bodyPart( new BodyPart(wavestream,MediaType.APPLICATION_OCTET_STREAM_TYPE));
Client c = Client.create();
WebResource r = c.resource("http://127.0.0.1:8080/webapp:);
response=r.path("transferFile").type(MediaType.MULTIPART_FORM_DATA).accept(MediaType.APPLICATION_XML).post(String.class, multiPart);
This works great - everything is ok. However I need this client working on Android and I have trouble with using jersey on that platform. So I used the normal way to send multipart message on android:
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter("http.socket.timeout", new Integer(90000)); // 90 second
HttpPost httpPost = new HttpPost("http://127.0.0.1:8080/webapp/transferFile");
httpPost.setHeader("Content-Type", MediaType.MULTIPART_FORM_DATA );
//tried with and without base64
byte [] encodedWavestream = Base64.encodeBytesToBytes(wavestream);
InputStream ins = new ByteArrayInputStream(encodedWavestream);
InputStreamBody body = new InputStreamBody(ins, "test" );
int send = ins.available();
MultipartEntity requestContent = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE );
requestContent.addPart("stream", body);
httpPost.setEntity(requestContent);
HttpResponse Response = client.execute(httpPost);
An this gives an annoying response from the server :
HTTP Status 400 - Bad Request
The request sent by the client was syntactically incorrect (Bad Request).
I check the server log files but there is nothing there. So I don't know what's the origin of this error. I have wrote a simple html page with a post formula and 'multipart/form-data' content-type and it also works! An auto-generated request from soapUI also works! Why my client does not work? Can anybody help?
There is bug in Jersey. See Chunked encoding problem.
This problem appears only for few clients (iOS, Android).
If you set the Content-Type to application/octet-stream, then the Jersey MessageWriter for the application/octet-stream will set the Content-Length and
not send as chunked transport method.
There is solution for Jersey Client:
ClientConfig config = new DefaultClientConfig();
config.getProperties().put(ClientConfig.PROPERTY_CHUNKED_ENCODING_SIZE, 32 * 1024);
But it doesn't work for the iOS's or Android's client.
So I tested Apache File Upload. Threre was another bug: "Stream ended unexpectedly".
Only Oreilly upload can upload file correct for all clients.
This is my code:
public Object[] getParametersAndFiles(HttpServletRequest request) throws IOException {
log.debug("OreillyUpload");
Properties params = new Properties();
LinkedHashMap files = new LinkedHashMap();
File tempDirectory = new File(System.getProperty("java.io.tmpdir"));
MultipartParser mp = new MultipartParser(request, 1*1024*1024); // 10MB
Part part;
while ((part = mp.readNextPart()) != null) {
String name = part.getName();
if (part.isParam()) {
// it's a parameter part
ParamPart paramPart = (ParamPart) part;
String value = paramPart.getStringValue();
params.put(name, value);
log.debug("param; name=" + name + ", value=" + value);
}
else if (part.isFile()) {
// it's a file part
FilePart filePart = (FilePart) part;
String fileName = filePart.getFileName();
if (fileName != null) {
// the part actually contained a file
File file = new File(tempDirectory,fileName);
long size = filePart.writeTo(file);
files.put(name, file);
log.debug("file; name=" + name + "; filename=" + fileName +
", filePath=" + filePart.getFilePath() +
", content type=" + filePart.getContentType() +
", size=" + size);
}
else {
// the field did not contain a file
log.debug("file; name=" + name + "; EMPTY");
}
}
}
return new Object[] {params, files};
}
And this is Jersey Server code (warning all Jersey Upload anotations (like as "#FormDataParam") should be removed):
#POST
#Path("uploadMarkup")
#Produces(MediaType.APPLICATION_JSON)
// #Consumes(MediaType.MULTIPART_FORM_DATA)
//// public void uploadMarkup(
// public JSONWithPadding uploadMarkup(
// #FormDataParam("markupFile") InputStream markupFile,
// #FormDataParam("markupFile") FormDataContentDisposition details,
// #FormDataParam("slideNum") int slideNum) {
public JSONWithPadding uploadMarkup(#Context HttpServletRequest request) {
Object[] data = uploadService.getParametersAndFiles(request);
...
}
I am working on my first Android Application. What I am trying to do is a POST request to a REST service I want the BODY of this request to be a JSON String.
I am using google's GSON to generate the JSON that is sent to the server. Here is the code doing POST request:
HttpPost requisicao = new HttpPost();
requisicao.setURI(new URI(uri));
requisicao.setHeader("User-Agent", sUserAgent);
requisicao.setHeader("Content-type", "application/json");
HttpResponse resposta = null;
//I can see the json correctly print on log with the following entry.
Log.d(TAG, "JSon String to send as body in this request ==>> " + jsonString);
//than I try to send JSon using setEntityMethod
StringEntity sEntity = new StringEntity(jsonString, "UTF-8");
requisicao.setEntity(sEntity);
resposta = httpClient.execute(requisicao);
resultado = HttpProxy.leRespostaServidor(resposta);
The response code is 400 BAD REQUEST and from the server log I can read the info. where it says the body was not correctly sent:
13:48:22,524 ERROR [SynchronousDispatcher] Failed executing POST /peso/cadastrar/maia.marcos#gmail.com
org.jboss.resteasy.spi.BadRequestException: Could not find message body reader for type: class java.io.Reader of content type: application/json
The code for the server side is a simple Seam Rest Service:
#POST
#Path("/cadastrar/{userEmail}")
#Consumes(MediaType.APPLICATION_JSON)
public String cadastraPeso(#PathParam("userEmail") String email, Reader jsonString)
{
LineNumberReader lnr = new LineNumberReader(jsonString);
try {
String json = lnr.readLine();
if(json != null)
{
log.debug("String json recebida do device ==>> " + json);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "OK - o e-mail processado foi ==>> " + email;
}
What could be wrong with the Android client code? I have researched the web and did not find any really useful information about this error.
[]s
Sorry folks, just turned out that the error was on the Rest service. I had change it and now it receives a String instead of the Reader object and it works as expected, the REST endpoint code on the server side now is:
#POST
#Path("/cadastrar/{userEmail}")
#Consumes(MediaType.APPLICATION_JSON)
public String cadastraPeso(#PathParam("userEmail") String email, String jsonString)
{
String json = jsonString;
if(json != null)
{
log.debug("String json received from device ==>> " + json);
}
return "OK - processed email ==>> " + email;
}
And the JSON string is correctly received on server side.
So de Android code above is working as expected.