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();
Related
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)
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!
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.
I'm getting the response like this:
HttpResponse response = httpclient.execute(httpget);
response.getStatusLine().toString());
In this case the response is:
HTTP/1.1 500 invalid user credentials
Ho do I get the message only, without the code?
**invalid user credentials**
Try this:
HttpResponse response = httpclient.execute(httpget);
StatusLine statusLine = response.getStatusLine();
String messageOnly = statusLine.getReasonPhrase();
int codeOnly = statusLine.getStatusCode();
Simple, do this
String responseStr = EntityUtils.toString(response.getEntity());
This will work!
You could simply get the message like this
String message = response.getStatusLine().toString().substring(12);
Use HttpURLConnection's getResponseMessage() See this
try this :
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
and then convert this input stream into string......
Use getReasonPhrase() method of StatusLine interface.
e.g.
HttpResponse response = httpclient.execute(httpget);
StatusLine statusLine = response.getStatusLine();
statusLine.getReasonPhrase()
I'm trying to perform a POST request to a server that wants the Content-Type set to application/json with name and email as some keys. Currently, I'm getting a 406 error, which I'm assuming is working on the server side, but android can't handle the response. How can I tweak the code to get a 200 response?
HttpClient client = new DefaultHttpClient();
HttpEntity entity;
try{
JSONObject j = new JSONObject();
j.put("name" , myName);
j.put("email", myEmail);
HttpPost post = new HttpPost(targetURL);
post.setHeader("Content-Type", "application/json");
StringEntity se = new StringEntity(j.toString(), HTTP.UTF_8);
se.setContentType("application/json");
post.setEntity(se);
HttpResponse response = client.execute(post);
entity = response.getEntity();
Log.d("response", response.getStatusLine().toString());
} catch(Exception e){Log.e("exception", e.toString());}
Does that look about right? Do I need one of those response handlers when creating the HttpClient?
This works for me with json-2.0.jar
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), MyApplication.HTTP_TIMEOUT); //Timeout Limit
HttpResponse response;
ArrayList<appResults> arrayList = new ArrayList<appResults>();
String resul;
try{
HttpGet get = new HttpGet(urls[0]);
response = client.execute(get);
/*Checking response */
if(response!=null){
InputStream in = response.getEntity().getContent(); //Get the data in the entity
resul = convertStreamToString(in);
Gson gson = new Gson();
Type listType = new TypeToken<ArrayList<appResults>>() {}.getType();
arrayList = gson.fromJson(resul, listType);
in.close();
of course in asynctask or thread.
But 406... it seems that your format on your webserver and your app are not consistent...