I am trying to send data to my server using HttpPost via the following code.
private boolean FacebookLogin(String url) {
boolean isDataSend = false;
try {
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
List<NameValuePair> value = new ArrayList<NameValuePair>();
value.add(new BasicNameValuePair("data", FacebookData()));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(value);
request.setEntity(entity);
HttpResponse res = client.execute(request);
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String bufstring = EntityUtils.toString(res.getEntity(),
"UTF-8");
isDataSend = true;
}
} catch (Exception e) {
}
return isDataSend;
}
Is there any way i can have a look at how the $_POST looks on the server end. so that it will be easier for me to code the server part.
You can write the received $_POST on a file. Sometimes I do that. It's not the most elegant solution, but it works fine.
Try using a http proxy (e.g. Fiddler) for debugging, it helps a lot in these cases. You can set up an emulator to use this proxy for network communications, so you can inspect the messages sent and received. Check out the emulator docs on how to configure it to use a proxy.
Related
In my android application I try to send a json object to a distant server, when I run it I get an error in httpclient.execute(httpPost)
This is a part of my code.
public static String GET(String url , JSONObject js){
try {
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Authorization", "Basic **********");
httpPost.setEntity(new StringEntity(js.toString()));
HttpClient httpclient = new DefaultHttpClient();
httpclient.execute(httpPost);
} catch (Exception e) {
Log.i("Console", "Error");
}
Any help please.
I guess your Problem is, that you try to run your Network Request from your Main Thread.
I would discourage you to use the Apache HTTP Client at all.
It became deprecated for Marshmallow, see here
Maybe try OkHttp. It offers you the possibility to run a request asynchronously.
I would like to send a file to a server. Currently the code I use includes deprecated classes. How can I update the code to be uptodate?
protected String doInBackground(String... params) {
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), params[0]);
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(server);
InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true); // Send in multiple parts if needed
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
//Do something with response...
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
I suggest you to use this library : retrofit
http://square.github.io/retrofit/
I use it on my project right now and it helps me a lot with my http requests.
Moreover the documentation is really good.
So i'm a web developer by trade but am making an app at the moment.
I've got a program on my PC which sends data from my PC to a database on my webhost.
What I'm after now, is to create an app that is able to download that data with a series of queries.
Are there any good resources around that would help me to develop some Java code, to connect to a server through my tablet when I'm out and about and download the information from my webhost when on a different wifi network?
Thanks chaps, any help is appreciated.
The way I handle it is that I just create a web page based on what I want to do. For example if I want to verify a login on an app I create a page that takes in a username and password.
On the device I just post the username and password values by using a HTTP post transaction.
Example:
public boolean LoginUser()
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("your URL comes here...");
try
{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
DataCrypt crypt = new DataCrypt();
try
{
this.Cryptemail = crypt.bytesToHex(crypt.encrypt(this.Email));;
this.Cryptpass = crypt.bytesToHex(crypt.encrypt(this.Password));
}
catch (Exception e)
{
DebugLog.log(e.getMessage());
}
nameValuePairs.add(new BasicNameValuePair("Password", this.Cryptpass));
nameValuePairs.add(new BasicNameValuePair("Mail", this.Cryptemail));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
BasicHttpResponse response = (BasicHttpResponse) httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String response = EntityUtils.toString(entity);
return true;
}
catch (Exception e)
{
DebugLog.log(e.getMessage());
return false;
}
return false;
}
EDIT: So you can just make a page that takes in some parameters that you want to base your query on and return the result in some way (for example by XML).
Hope this helps you out! :)
I want to send the JSON text {} to a web service and read the response. How can I do this from android? What are the steps such as creating request object, setting content headers, etc.
My code is here
public void postData(String result,JSONObject obj) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 10000);
HttpConnectionParams.setSoTimeout(myParams, 10000);
String json=obj.toString();
try {
HttpPost httppost = new HttpPost(result.toString());
StringEntity se = new StringEntity(obj.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
String temp = EntityUtils.toString(response.getEntity());
Log.i("tag", temp);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
what mistake i have done plz correct me because it shows me an bad request error
but when i do post in poster it shows me status as Successfull 200 ok
I do this with
httppost.setHeader("Content-type", "application/json");
Also, the new HttpPost() takes the web service URL as argument.
In the try catch loop, I did this:
HttpPost post = new HttpPost(
"https://www.placeyoururlhere.com");
post.setHeader(HTTP.CONTENT_TYPE,"application/json" );
List<NameValuePair> nameValuePairs = new
ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("json", json));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpClient client = new DefaultHttpClient();
HttpResponse resp = client.execute(post);
HttpEntity entity = resp.getEntity();
response = EntityUtils.toString(entity);
You can add your nameValurPairs according to how many fields you have.
Typically the JSON might become really huge, which I will then suggest gzipping it then sending, but if your JSON is fairly small and always the same size the above should work for you.
If it is a web service and not RestAPI call then, you can get the WSDL file from the server and use a SOAP Stub generator to do all the work of creating the Request objects and the networking code for you, for example WSClient++
If you wish to do it by yourself then things get a little tricky. Android doesn't come with SOAP library.
However, you can download 3rd party library here: http://code.google.com/p/ksoap2-android/
If you need help using it, you might find this thread helpful: How to call a .NET Webservice from Android using KSOAP2?
If its a REST-API Call like POST or GET to be more specific then its is very simple
Just pass a JSON Formatted String object in you function and use org.json package to parse the response string for you.
Hope this helps.
I'm trying to simulate a process like "cache validation" in my application.
I will download a new version of my webapplication on the device (android-based), but I only want to download a new version of the files, based in a etag comparision.
Does anyone a example of how use the Etag mechanism in Android?
You can access the ETag field from a HttpURLConnection object such as like this:
HttpURLConnection conn = (HttpURLConnection)new URL(url).openConnection();
String etag = conn.getHeaderField("ETag");
Of course, you will need to make sure that the server you are testing this against supports ETags.
Maybe class "HttpRequest" from this library (kevinsawicki) will help you.
For example:
File latest = new File("/data/cache.json");
HttpRequest request = HttpRequest.get("http://google.com");
//Copy response to file
request.body(latest);
//Store eTag of response
String eTag = request.eTag();
//Later you can check if changes exist
boolean unchanged = HttpRequest.get("http://google.com")
.ifNoneMatch(eTag)
.notModified();
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
HttpResponse response = httpClient.execute(httpPost);
Log.d("Http Response:", response.getFirstHeader("etag").toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
You can refer to the specific implement of ShallowEtagHeaderFilter performing etag generation and validation in Spring.