Android do PATCH/PUT to server - java

I'm having this issue and I need to put or patch data to the server. I know how to do a standard post, but how can I do this PATCH or PUT to the server?
The URL to the server is PATCH to www.example.com/api/documents and parameter is doc_id(integer).
This is what I currently have
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("content-type", "application/json");
httpPost.setHeader("accept-charset", "utf8");
try {
HttpResponse response = httpClient.execute(httpPost);
responseString = EntityUtils.toString(response.getEntity());
} catch (Exception e) {
Log.e("Request exception:", "excpetion", e);
}
return responseString;
But this code I think is wrong as hell :)

This is the most common way---
Creating jsonObj and putting json values:
JSONObject jsonObj = new JSONObject();
jsonObj .put("doc_id", <put your value> + "");
String response = callPutService(source, password, callingAPI, jsonObj);
This is the callPutService that is called:
public String callPutService(String userName, String password,
String type, JSONObject jsonObject) {
String line = null, jsonString = "";
HttpResponse response = null;
InputStream inputStream = null;
try {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.
setConnectionTimeout
(client.getParams(), 20000); // Timeout Limit
HttpPut put = new HttpPut(WEBSERVICE + type);
StringEntity se = new StringEntity(jsonObject.toString());
se.setContentType("application/json;charset=UTF-8");
put.setHeader("Authorization",
"basic " + Base64.
encodeToString((userName + ":" + password).getBytes(),
Base64.URL_SAFE | Base64.NO_WRAP));
put.setEntity(se);
response = client.execute(put);
int responseCode = response.getStatusLine().getStatusCode();
if(responseCode == 200){
//do whatever
}
} catch (Exception e) {
e.printStackTrace();
}
return jsonString;
}

Related

how to read it into a string without using a readline of String Buffer in android

public class HttpPosrHitter {
public static String getJSONfromURL(String url, String member_id,
String phonenumber) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("memberid", member_id));
pairs.add(new BasicNameValuePair("numbers", phonenumber));
httppost.setEntity(new UrlEncodedFormEntity(pairs));
// http post
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, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = "";
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());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return result;
}
}
This is class from which i am Post Phone Number to web service and getting response .
when i Post Number of Phone which has 15 to 20 contact i am getting response . but when i post number which has 150 contact i am not getting response one at a time i have to relaunch app two time then i am getting response . i dont know where i am doing mistake . even i am unable to read phone large file in chunks with fixed size buffer.
Just to solve all your potential bugs in one single shot: is there anything preventing you from using Retrofit and GSON or Jackson?
Each time I see such JSON/InputStream/URLConnection/... questions, I keep wondering why people keep on spending time to reinvent basic stuff instead of actually writing apps.
public class HttpPosrHitter {
public static String getJSONfromURL(String url, String member_id,
String phonenumber) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("memberid", member_id));
pairs.add(new BasicNameValuePair("numbers", phonenumber));
httppost.setEntity(new UrlEncodedFormEntity(pairs));
// http post
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity); //changes Made
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return result;
}
}

For each loop is not executing when uploaded at 000webhost server

I have an application that post data to a php file in an online server. When the post is done i get a garbage of html code. In it says I have a php error and that is Invalid argument supplied for each() on line 33. However this problem does not occur if I run it in localhost. I don't understand why this problem is occuring. So someone please help me to solve it.
The following is my jsonparser Class
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getandpostJSONFromUrl(String url, String method,JSONArray name) {
// Making HTTP request
try {
// defaultHttpClient
if (method == "POST") {
HttpParams params = new BasicHttpParams();
//params.setParameter("data", auth);
HttpClient httpclient = new DefaultHttpClient(params);
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("json", name.toString()));
for (NameValuePair nvp : postParams) {
String name2 = nvp.getName();
String value = nvp.getValue();
Log.d("NameValue pair content", ""+name2+""+value);
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams,HTTP.UTF_8);
httpPost.setEntity(entity);
HttpResponse response = httpclient.execute(httpPost);
String responseBody = EntityUtils.toString(response.getEntity());
Log.d("",responseBody);
}
if (method == "GET") {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (method == "POST") {
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
} catch (Exception e) {
Log.e("Buffer error", "Buffer error" + e);
}
} else if (method == "GET") {
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
}
// return JSON String
return jObj;
}
}
The following is the php file on the server
<?php
header('Content-type: application/json');
/*define('DB_NAME', 'a1422982_sshop');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');*/
define('DB_NAME', 'onlineshop');
define('DB_USER', 'shop');
define('DB_PASSWORD', 'pass');
define('DB_HOST', 'mysql28.000webhost.com');
$link = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);
if(!$link){
die('could not connect: '.msql_error());
}
$db_selected=mysql_select_db(DB_NAME, $link);
if(!$db_selected){
die('Can not use '.DB_NAME.':'.mysql_error());
}
//var_dump(json_decode ($_POST['json'])));
if($_POST['json']){
$parsed = json_decode($_POST['json'],TRUE);
$i=0;
foreach ($parsed as $obj) {
$ProductName = $obj['Name'];
$ProductQuantity= $obj['Quantity'];
$sql="Update productlist Set Quantity='$ProductQuantity' where Name='$ProductName';";
$retval = mysql_query( $sql, $link );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
$i++;
echo $ProductName." ".$ProductQuantity;
}
}else{
echo "empty";
}
?>
there's a missing options on your HttpPost request set the entity metadata and the resulting entity as string.
In your java code you can do this:
Map<String, String> postData = new HashMap<String, String>();
postData.put("KEY", "yourvalue");
JSONObject holder = new JSONObject(postData);
StringEntity jsonStringEntity = new StringEntity(holder.toString());
httpost.setEntity(jsonStringEntity);
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json");
in that way your PHP code could actually parse your post data since json_decode() expecting json as parameter.

How to send Json String using REST to java webservice in Parameter in android?

Fiends, i sending JSON String with three parameters to java web service method. but on java side method cant print in console. Please guide me what i have to change from below code?
String json = "";
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 10000);
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpPost httpPost = new HttpPost(url);
HttpGet httpGet = new HttpGet(url);
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("name", "ghanshyam");
jsonObject.put("country", "India");
jsonObject.put("twitter", "ghahhd");
json = jsonObject.toString();
StringEntity se = new StringEntity(json);
se.setContentEncoding("UTF-8");
se.setContentType("application/json");
// 6. set httpPost Entity
System.out.println(json);
httpPost.setEntity(se);
httpGet.se
// 7. Set some headers to inform server about the type of the content
//httpPost.addHeader( "SOAPAction", "application/json" );
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
//String s = doGet(url).toString();
Toast.makeText(getApplicationContext(), "Data Sent", Toast.LENGTH_SHORT).show();
Use the following code to post the json to Java web-service: and get the resopnse as a string.
JSONObject json = new JSONObject();
json.put("name", "ghanshyam");
json.put("country", "India");
json.put("twitter", "ghahhd");
HttpPost post = new HttpPost(url);
post.setHeader("Content-type", "application/json");
post.setEntity(new StringEntity(json.toString(), "UTF-8"));
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse httpresponse = client.execute(post);
HttpEntity entity = httpresponse.getEntity();
InputStream stream = entity.getContent();
String result = convertStreamToString(stream);
and Your convertStremToString() method will be as follows:
public static String convertStreamToString(InputStream is)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
is.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return sb.toString();
}

Getting "Invalid JSON primitive" error while trying to get data from WebService

I'm working on an android app and I want to get some data from a WebService. I'm using this code to get JSON data from the WebService.
TextView textv=(TextView) findViewById(R.id.textv);
try {
HttpClient client = new DefaultHttpClient();
String URL = "http://server/WebService.asmx/Get_ActiveFair";
HttpPost post = new HttpPost(URL);
post.setHeader("Content-Type", "application/json; charset=utf-8");
HttpResponse responsePost = client.execute(post);
HttpEntity resEntityPost = responsePost.getEntity();
if (resEntityPost != null)
{
String response=EntityUtils.toString(resEntityPost);
Log.e("XXX",response);
textv.setText(response);
}
} catch (Exception e) {
e.printStackTrace();
textv.setText(e.toString());
Log.e("error!!",e.toString());
}
It works correctly an I get the data like this:
{
"d": "{\"Id\":2,\"Name\":\"Fair Name \",\"IsActive\":true,\"Date_Start\":\"\\/Date(1383343200000)\\/\",\"Date_End\":\"\\/Date(1384034400000)\\/\",\"Url_Map\":null,\"Details\":\"Fair Details \",\"Address\":\"FairAdress \",\"VisitingInfo\":\"Fair Visiting Info\",\"Contact\":null,\"Transportation\":\" Fair Transportation Info \"}"
}
But when I want to use another method in the webservice which needs to get FairId I get the result:
{
"Message": "Invalid JSON primitive: FairId.",
"StackTrace": " at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)\r\n at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)",
"ExceptionType": "System.ArgumentException"
}
And here is my code to run the Get_EventList method:
TextView textv=(TextView) findViewById(R.id.textv);
try {
HttpClient client = new DefaultHttpClient();
String URL = "http://server/WebService.asmx/Get_EventList";
HttpPost post = new HttpPost(URL);
List<NameValuePair> postParameters;
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("FairId", "2"));
post.setEntity(new UrlEncodedFormEntity(postParameters));
post.setHeader("Content-Type", "application/json; charset=utf-8");
HttpResponse responsePost = client.execute(post);
HttpEntity resEntityPost = responsePost.getEntity();
if (resEntityPost != null)
{
String response=EntityUtils.toString(resEntityPost);
Log.e("XXX",response);
textv.setText(response);
}
} catch (Exception e) {
e.printStackTrace();
textv.setText(e.toString());
Log.e("hata!!",e.toString());
}
What can be the problem? How can I solve it?
I solve the problem by sending FairId to WebService with JSONObject. Here is my new code:
TextView textv=(TextView) findViewById(R.id.textv);
try {
HttpClient client = new DefaultHttpClient();
String URL = "http://server/WebService.asmx/Get_EventList";
HttpPost post = new HttpPost(URL);
JSONObject json = new JSONObject();
json.put("FairId", "2");
StringEntity se = new StringEntity( json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
HttpResponse responsePost = client.execute(post);
HttpEntity resEntityPost = responsePost.getEntity();
if (resEntityPost != null)
{
String response=EntityUtils.toString(resEntityPost);
Log.e("XXX",response);
textv.setText(response);
}
} catch (Exception e) {
e.printStackTrace();
textv.setText(e.toString());
Log.e("hata!!",e.toString());
}

Parse Json Arabic text

I can't parse Arabic/Persian text from SQL database. Everything is set to UTF-8. My SQL database text is set to utf8_general_ci. JSON parser is set to UTF-8 too.
Text is shown good in English. But when I use Arabic/Persian text in database, android shows text as ???????.
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
I have been r & d around a day and finally success to parse my arabic json response getting from server using following code.So, may be helpful to you.
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
params.setBooleanParameter("http.protocol.expect-continue", false);
HttpClient httpclient = new DefaultHttpClient(params);
HttpPost httppost = new HttpPost(Your_URL);
HttpResponse http_response= httpclient.execute(httppost);
HttpEntity entity = http_response.getEntity();
String jsonText = EntityUtils.toString(entity, HTTP.UTF_8);
Log.i("Response", jsonText);
Now, use jsonText for your further requirement.
Thank You
Maybe the problem is on server side. Check the raw String you got from the Server to see if it is correctly formatted.
I think it can help you by storing it as clob/blob, since once you have the bytes which were convereted from UTF-8 at server side, any client side code can also then using various String encoding formats to display the test.
Or my other advice, use a webview to display it, its more mature to handle these nuances.

Categories