Android HttpPost without parameter name - android

I've used POST methods many times in the past but got this weird web service. It works fine on a chrome extension but i am unable to get this response using android . Please add anything in the code if missing
Here is the code i am using
HttpParams param = new BasicHttpParams();
param.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpClient httpclient = new DefaultHttpClient(param);
HttpPost httppost = new HttpPost(url);
Utils.showLogs(MyConstants.TAG, "ApplicationURL: " + url);
httppost.setHeader("Content-type", contentType);
HttpConnectionParams.setConnectionTimeout(param, MyConstants.WEBSERVICE_TIMEOUT);
HttpConnectionParams.setSoTimeout(param, MyConstants.WEBSERVICE_TIMEOUT);
String response = null;
try {
if (jsonObject == null) {
StringEntity entity = new StringEntity(json, HTTP.UTF_8);
httppost.setEntity(entity);
} else {
StringEntity stringEntity = new StringEntity(jsonObject.toString());
httppost.setEntity(stringEntity);
}
// Execute HTTP Post Request
HttpResponse httpResponse = httpclient.execute(httppost);
final int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return MyConstants.SERVER_NOT_RESPONDING;
}
HttpEntity httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
Thanks

Did you add <uses-permission android:name="android.permission.INTERNET" /> in AndroidManifest.xml ?
If not, add this should be fine!

Related

Get the XML entity passed in body - HTTP Put method in Android

I wanted to retrieve the XML entity passed in body of HTTP Put method. I used the below code,
DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
conn.bind(serverSocket.accept(), new BasicHttpParams());
HttpRequest request = conn.receiveRequestHeader();
conn.receiveRequestEntity((HttpEntityEnclosingRequest)request);
HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity();
System.out.println(EntityUtils.toString(entity));
I could get the norma strings, but when trying to pass the XML entity, I could not even see the print statement.
I hope this code help you.
HttpPost httppost = new HttpPost(SERVICE_EPR);
StringEntity se = new StringEntity(SOAPRequestXML,HTTP.UTF_8);
se.setContentType("text/xml");
httppost.setHeader("Content-Type","application/soap+xml;charset=UTF-8");
httppost.setEntity(se);
HttpClient httpclient = new DefaultHttpClient();
BasicHttpResponse httpResponse =
(BasicHttpResponse) httpclient.execute(httppost);
response.put("HTTPStatus",httpResponse.getStatusLine().toString());
PFB the solution,
DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
params = new BasicHttpParams();
conn.bind(socket, params);
//Extracting the information from the requested URI
HttpRequest request = conn.receiveRequestHeader();
conn.receiveRequestEntity((HttpEntityEnclosingRequest)request);
HttpEntity httpEntity = ((HttpEntityEnclosingRequest)request).getEntity();
if(httpEntity != null){
InputStream instream = httpEntity.getContent();
try {
// do something useful
String myString = IOUtils.toString(instream, "UTF-8");
Log.e(TAG,">>>> http body > "+myString);
} finally {
instream.close();
}
}
Don't put any log or print statements using the data you received, I was getting 'Content already consumed' exception. I had used several logs using the httpEntity i received and that was causing the problem for me. I commented those(marked yellow) and started working.
PF the Apache doc for reference,
http://hc.apache.org/httpcomponents-core-ga/tutorial/pdf/httpcore-tutorial.pdf

How to post JSON Stringer to Server without any deprecation warning

I used to post json stringer using the following code but having lot of deprecation warning.Can anyone help me out to show me the correct way for POSTing.Please have a look on my code that i'm using for posting currently.
HttpPost httppost = new HttpPost(F_URL);
System.out.println("URL...." + F_URL);
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-Type", "application/json");
JSONStringer jsonStringer = new JSONStringer().object()
.key("putmicdata").object().key("CompanyID")
.value(companyid).key("ValueHeader")
.value(valueheader).key("ValueHeaderDetail")
.value(valueheaderdetail).endObject();
StringEntity entity = new StringEntity(
jsonStringer.toString());
System.out.println("String...."
+ jsonStringer.toString());
entity.setContentType(new BasicHeader(
HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(entity);
response = httpclient.execute(httppost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
System.out.println("StatusCode for MIC" + statusCode);
if (response != null) {
HttpEntity httpEntity = response.getEntity();
total = EntityUtils.toString(httpEntity);
dbhelper.getWritableDatabase();
dbhelper.DELETE_MICUOMINTERNAL(loc);
dbhelper.closeDatabase();
}
result = "success";
you can use HttpUrlConnectionor if you want just opening a webaddress just use
new URL("youraddress.com").openStream();

Android CouchDB {"error":"bad_request","reason":"invalid_json"}

While trying to Create a new Document in my IrisCouch Database, i am always getting following error:
{"error":"bad_request","reason":"invalid_json"}
This is the relevant part of my function:
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://username.iriscouch.com:6984/mydb");
StringEntity entity = new StringEntity(body);
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpResponse httpResponse = httpClient.execute(httpPost);
System.out.println(httpResponse.toString()) ;
HttpEntity httpEntity = httpResponse.getEntity();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(httpEntity.getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
System.out.println("body: " + body);
} catch (Exception e) {
e.printStackTrace();
}
Here is my System.out of "body":
{"bild1":"","bild2":"","bild3":"","bild4":"","bild5":"","bild6":"","bild7":"","bild8":"","bild9":"","bild10":"","name":"","plz":0,"ort":"","strasse":"","n_koordinate":0,"e_koordinate":0,"beschreibung":"","groesse":"< 50m²","sitzplaetze":"< 50","grillstellen":"1","reservierung":false,"res_name":"","res_tele":"","res_weiteres":"","wc":true,"behindi":false,"dach":true,"kinderfreundl":false,"auto":false,"kinderwagen":false,"einkauf":false,"datum":"2015-07-01-14:12:01:856","bewertung":0,"anz_bewertung":0}
The JSON is valid. Tested it with jsonlint.com JSON Validator.
What could i do? Thanks in advance!
Perhaps the unicode superscript 2 (²) is bothering it?
Not sure which library this HttpPost is, but seems a lot like the HttpWebRequest, so try setting your header this way:
httpPost.setHeader("Content-type", "application/json charset=utf-8");
It could also be that the HttpPost class doesn't properly encode strings.
(I haven't pasted this in my Visual studio, so just a shot in the dark)

Android http post works with string but not xstream

I'm making a droid app that uses a web service. I have it working when I pass in a string, but when I try and use Xstream it doesn't work. I have printed out the xml strings from both the Xstream and my own and they are identical. Without xstream it looks like this and works
`HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://softeng.cs.uwosh.edu/students/cs342g6/login.php");
Boolean response = false;
try
{
String test = "<Login>" +
"<password>" + "lernrane" + "</password>" +
"<user_name>" + "jake#jake.com" + "</user_name>" +
"</Login>";
StringEntity se = new StringEntity(test,
HTTP.UTF_8);
se.setContentType("text/xml");
httppost.setEntity(se);
System.out.println("MADE IT TO RESPONSE");
HttpResponse httpresponse = httpclient.execute(httppost);
HttpEntity resEntity = httpresponse.getEntity();
String resp = EntityUtils.toString(resEntity);
System.out.println(resp);
response = convertToBool(resp);`
But when I use xstream it looks like this and fails
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://softeng.cs.uwosh.edu/students/cs342g6/login.php");
Boolean response = false;
try
{
LoginObject login = new LoginObject();
login.setUserName("jake#jake.com");
login.setPassword("lernrane");
XStream xstream = new XStream();
xstream.alias("Login", LoginObject.class);
String xml = xstream.toXML(login);
System.out.println(xml);
StringEntity se = new StringEntity(xml,
HTTP.UTF_8);
se.setContentType("text/xml");
httppost.setEntity(se);
System.out.println("MADE IT TO RESPONSE");
HttpResponse httpresponse = httpclient.execute(httppost);
HttpEntity resEntity = httpresponse.getEntity();
String resp = EntityUtils.toString(resEntity);
System.out.println(resp);
response = convertToBool(resp);
My web service looks like this
$dom = new domDocument;
$dom = simplexml_load_file('php://input');
$xml = simplexml_import_dom($dom);
$user = Users::find_by_user_name($xml->user_name);
if($user)
{
if($user->password == $xml->password)
{
echo "TRUE";
}
}
else
echo "FALSE";
Ignore the odd looking query, I am using active record and I know it works correctly...thanks
I figured it out... When I printed out my xml user_name looked like this user__name eventhough it was clearly named user_name. There must be some type of char set conflict so I just renamed it without the underscore.

Sending Video using HTTP Post Multipart entity

What I want I want to send a video from my SDcard to a server. I also want to send some parameters/value with it.
I have tried I have tried the following code:
public String SendToServer(String aUrl,File aFile)
{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(aUrl);
try
{
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("file", new FileBody(aFile));
entity.addPart("video[title]", new StringBody("testVideo"));
entity.addPart("video[type]", new StringBody("1"));
httpPost.setEntity(entity);
HttpContext localContext = new BasicHttpContext();
// Bind custom cookie store to the local context
localContext.setAttribute(ClientContext.COOKIE_STORE, Globals.sessionCookie);
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity resEntity = response.getEntity();
String Response = "";
if (response != null)
{
Response = EntityUtils.toString(resEntity);
}
return Response;
}
catch (IOException e)
{
e.printStackTrace();
}
return "Exception";
}
What is the problem When I run this code, I get stuck at this line
HttpResponse response = httpClient.execute(httpPost, localContext);
I get no exception, no response nothing at all. Can anyone please guide me, what is the problem in here?
The above code in my question was perfect, but I had the network problem. My device was connected to a hotspot(Connectify Software). When I connected to the original network, this code worked perfect.
I recommend you people to never trust a hotspot for this kind of functionality.
try using this way if want to send as content or esle I will upload the project by tonight
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(filePath), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true); // Send in multiple parts if needed
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);

Categories

Resources