I created the JSON object using this code:
json = new JSONObject();
try {
json.put("success", true);
JSONObject jCustomer = new JSONObject();
jCustomer.put("LOGICALREF", 0);
jCustomer.put("CODE", "");
EditText definitionText = (EditText) findViewById(R.id.definitionText);
jCustomer.put("DEFINITION_", definitionText.getText().toString());
jCustomer.put("ISPERSCOMP", isPersComp);
EditText taxOrIdNoText = (EditText) findViewById(R.id.taxOrIdNoText);
if (isPersComp == 1){
jCustomer.put("TAXNR", "");
jCustomer.put("TCKNO", taxOrIdNoText.getText().toString());
} else {
jCustomer.put("TAXNR", taxOrIdNoText.getText().toString());
jCustomer.put("TCKNO", "");
}
EditText taxOfficeText = (EditText) findViewById(R.id.taxOfficeText);
String taxOfficeString = taxOfficeText.getText().toString();
if (taxOfficeString.isEmpty() || taxOfficeString == null){
jCustomer.put("TAXOFFICE", "TCKIMLIK");
} else {
jCustomer.put("TAXOFFICE", taxOfficeString);
}
EditText emailText = (EditText) findViewById(R.id.emailText);
jCustomer.put("EMAILADDR", emailText.getText().toString());
EditText address1Text = (EditText) findViewById(R.id.address1Text);
jCustomer.put("ADDR1", address1Text.getText().toString());
EditText address2Text = (EditText) findViewById(R.id.address2Text);
jCustomer.put("ADDR2", address2Text.getText().toString());
jCustomer.put("CITY", cityString);
jCustomer.put("CITYCODE", cityNo);
jCustomer.put("TOWN", townString);
jCustomer.put("TOWNCODE", townNo);
EditText inChargeText = (EditText) findViewById(R.id.inChargeText);
jCustomer.put("INCHARGE", inChargeText.getText().toString());
EditText nameText = (EditText) findViewById(R.id.nameText);
jCustomer.put("NAME", nameText.getText().toString());
EditText surnameText = (EditText) findViewById(R.id.surnameText);
jCustomer.put("SURNAME", surnameText.getText().toString());
EditText phoneNo1Text = (EditText) findViewById(R.id.phoneNo1Text);
jCustomer.put("TELNRS1", phoneNo1Text.getText().toString());
EditText phoneNo2Text = (EditText) findViewById(R.id.phoneNo2Text);
jCustomer.put("TELNRS2", phoneNo2Text.getText().toString());
json.put("data", jCustomer);
new postJSON().execute();
} catch (Exception e){
e.printStackTrace();
}
postJSON is a private class that extends AsyncTask. Here is its code:
private class postJSON extends AsyncTask<Void, Void, Void>{
ProgressDialog progressDialog;
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(NewCustomerInfoActivity.this);
progressDialog.setMessage("Yeni müşteri kaydediliyor. Lütfen bekleyiniz.");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Don't know what to do here...
return null;
}
protected void onPostExecute(Void requestResult) {
super.onPostExecute(requestResult);
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
Now I have to post this to the server as body, and I don't know where to begin. Most tutorials on the internet use libraries that I can't add or find, or are too complicated for me to understand. I already created a webRequest function but I use it to get the JSON objects from the server and it works:
public String getJson (String urlAdress, Boolean postRequest){
URL url;
String jString = "";
try {
url = new URL(urlAdress);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(15001);
connection.setReadTimeout(15001);
connection.setDoInput(true);
if (postRequest){
connection.setRequestMethod("POST");
} else {
connection.setRequestMethod("GET");
}
int requestResponse = connection.getResponseCode();
if (requestResponse == HttpsURLConnection.HTTP_OK){
String line;
BufferedReader buffer = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = buffer.readLine()) != null){
jString += line;
}
} else {
jString = "";
}
} catch (Exception e){
e.printStackTrace();
return null;
}
return jString;
}
How do I add the JSON object to the url as body and post it? Will the function above suffice when it comes to posting it?
Edit after adding the recommended codes (outputstream etc.):
Web Service code by server's side:
#RequestMapping(value = "/newCustomer", method = RequestMethod.POST, headers = "Accept=application/json; charset=utf-8", produces = "application/json")
private ResponseEntity<String> newCustomer (#RequestParam(value = "deviceId") String _deviceId,
#RequestParam(value = "ssid") String _ssid,
#RequestBody String _incomingData, //(value = "incomingData")
HttpServletRequest _request,HttpServletResponse _response){
Object responseMap = null;
boolean response = false;
System.out.println(_incomingData);
Incoming data to the server:
deviceId=ec5f501b01c54038&ssid=QUCGFHA7ILIT3E9O8BHTD5NE4H&%7B%22success%22%3Atrue%2C%22data%22%3A%7B%22LOGICALREF%22%3A0%2C%22CODE%22%3A%22%22%2C%22DEFINITION_%22%3A%22asdasd%22%2C%22ISPERSCOMP%22%3A0%2C%22TAXNR%22%3A%22564564%22%2C%22TCKNO%22%3A%22%22%2C%22TAXOFFICE%22%3A%22ghfgh%22%2C%22EMAILADDR%22%3A%22asdasd%22%2C%22ADDR1%22%3A%22asdas%22%2C%22ADDR2%22%3A%22asdasd%22%2C%22CITY%22%3A%22Amasya%22%2C%22CITYCODE%22%3A5%2C%22TOWN%22%3A%22Hamam%C3%83%C2%B6z%C3%83%C2%BC%22%2C%22TOWNCODE%22%3A3%2C%22INCHARGE%22%3A%22xcvxcb%22%2C%22NAME%22%3A%22xcbxcb%22%2C%22SURNAME%22%3A%22gxcb%22%2C%22TELNRS1%22%3A%22456456%22%2C%22TELNRS2%22%3A%225456456%22%7D%7D=
ssId and deviceId were NOT supposed to be sent as a part of the body. Yet here it is.
The function I use at the moment:
public String postJson (String urlAdress, Boolean postRequest, JSONObject json){
URL url;
String jString = "";
try {
url = new URL(urlAdress);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(15001);
connection.setReadTimeout(15001);
connection.setDoInput(true);
if (postRequest){
connection.setRequestMethod("POST");
} else {
connection.setRequestMethod("GET");
}
connection.connect();
OutputStreamWriter request = new OutputStreamWriter(connection.getOutputStream());
request.write(json.toString());
request.flush();
int requestResponse = connection.getResponseCode();
if (requestResponse == HttpsURLConnection.HTTP_OK){
} else {
jString = "";
}
} catch (Exception e){
e.printStackTrace();
return null;
}
return jString;
}
Add line connection.setDoOutput(true); below the connection.setDoInput(true);.
Then get the outputStream from your HttpURLConnection and write the json there, something like this:
OutputStream os = connection.getOutputStream();
os.write(json.toString().getBytes("UTF-8"));
os.close();
Use Retrofit,
blog - https://futurestud.io/tutorials/retrofit-getting-started-and-android-client
library - http://square.github.io/retrofit
Its easy to implement just using POJO class with GSON.
Without external library,
Try this,
public static String POST(Activity context, String connectionURL,
YOURBODYOBJECT mparms) throws Exception {
try {
url = new URL(connectionURL);
connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(30000);
connection.setConnectTimeout(30000);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded"); // Change header for your convience.
connection.setChunkedStreamingMode(0);
connection.setRequestMethod("POST");
connection.connect();
request = new OutputStreamWriter(connection.getOutputStream());
request.write(mparms);// pass your body content
request.flush();
HTTP_RESPONSE_CODE = connection.getResponseCode();
switch (HTTP_RESPONSE_CODE) {
case HttpURLConnection.HTTP_OK:
isr = new InputStreamReader(connection.getInputStream());
reader = new BufferedReader(isr);
sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
// response variable.
response = sb.toString();
isr.close();
reader.close();
return response.trim();
case HttpURLConnection.HTTP_UNAUTHORIZED:
return String.valueOf(HTTP_RESPONSE_CODE).trim();
case HttpURLConnection.HTTP_BAD_REQUEST:
isr = new InputStreamReader(connection.getErrorStream());
reader = new BufferedReader(isr);
sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
response = sb.toString();
isr.close();
reader.close();
return response.trim();
case HttpURLConnection.HTTP_INTERNAL_ERROR:
isr = new InputStreamReader(connection.getErrorStream());
reader = new BufferedReader(isr);
sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
response = sb.toString();
isr.close();
reader.close();
return response.trim();
default:
return response.trim();
}
} catch (Exception e) {
// Error
return e.getMessage();
} finally {
connection.disconnect();
}
}
Related
A script on my server returns an array of SQL rows. An appropriate curl returns string which is correct:
[{"ID":"1","DATETIME":"2021-05-30 21:29:27","SETPOINT":"45.22","LUMIN":"65.98","DIRECTION":"LOG"},{"ID":"1","DATETIME":"2021-05-30 15:55:34","REVS":"2.11934","ROTATION":"1","DIRECTION":"LOG","POSITION":"12"}]
However, while parsing it in my Android application, I am getting an error org.json.JSONException: Value http of type java.lang.String cannot be converted to JSONArray. Closer investigation (Toast printing) to what is passed indicated that the application is receiving the remote script's address http://<ip>/readLatest.php, and not the array, as seen with the curl query.
What seems to be a problem? Other answers as to similar questions were not helpful
Async task:
public class DataGetter extends AsyncTask<String, Void, String[]> {
Context context;
private GetListener GetListener;
public String jsonString;
public boolean passed_successfully;
DataGetter(Context ctx, GetListener listener) {
this.context = ctx;
this.GetListener = listener;
this.passed_successfully = false;
}
#Override
protected String[] doInBackground(String... params) {
String ip = params[0];
String scriptname = params[1];
String db = params[2];
String urladress = "http://" + ip + "/"+ scriptname +".php";
try {
URL url = new URL(urladress);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
OutputStream os = connection.getOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(os, "UTF-8");
String data = URLEncoder.encode("database", "UTF-8") + "=" + URLEncoder.encode(db, "UTF-8");
writer.write(data);
writer.flush();
writer.close();
BufferedReader reader = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
break;
}
connection.disconnect();
return new String[] {sb.toString(), scriptname};
} catch (Exception e) {
return new String[] {e.getMessage()};
}
}
#Override
protected void onPostExecute(String... result) {
GetListener.passJSONGet(result);
}
}
Part of appropriate Activity:
#Override
public void passJSONGet(String... result) {
String jsonstring = result[0];
try {
showToast(jsonstring);
this.jsonArray = new JSONArray(jsonstring);
this.printControls(jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void printControls(JSONArray jsonArray) throws JSONException {
String lumin = jsonArray.getJSONObject(1).getString("LUMIN");
this.luminval.setText(String.format("%s", lumin));
int position = Integer.parseInt(jsonArray.getJSONObject(0).getString("POSITION"));
this.positionval.setText(String.format("%s", position));
}
I have this method which is giving a network on main thread. I want to make this api call on a separate thread using asynctask.
However, the business logic prohibits me to use non static methods. The code is:
public static JSONObject acceptOrder(String orderId, Integer loadsToAccept) throws IOException{
BufferedReader reader = null;
JSONObject resultOrder = null;
AsyncTask asyncTask = new AsyncTask() {
#Override
protected Object doInBackground(Object[] objects) {
return null;
}
};
HttpURLConnection conn = (HttpURLConnection) new URL(GlobalConfig.getInstance().GetGoVulcanConfig().getUrl() + "/api/Order/ProcessAcceptedOrder?acceptedLoads=" + loadsToAccept + "&haulerId=" + GlobalConfig.getInstance().GetGoVulcanConfig().getHaulerId() + "&orderId=" + orderId).openConnection();
conn.setDoOutput(true);
//conn.setFixedLengthStreamingMode(jsonString.length());
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept","application/json");
InputStream inputStream = conn.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String inputLine;
while ((inputLine = reader.readLine()) != null)
buffer.append(inputLine);
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
try {
resultOrder = new JSONObject(buffer.toString());
}catch (JSONException ex){
Log.d(ex.getMessage(), "acceptOrder: ");
}
conn.disconnect();
reader.close();
return resultOrder;
}
How can I do this?
This is the form that i do to request POST or GET, I hope can help you
1) I have my class with all the request
public class RequestManager {
public static class requestPostExample extends AsyncTask<String, Void, String>{
Context context;
int exampleId;
String exampleData;
//interface to get the response in the activity
Public AsynkTaskRespone response = null;
public requestPostExample(Context context, int exampleID, String exampleData){
this.context = context;
this.exampleId = exampleID;
this.exampleData = exampleData;
}
#Override
protected String doInBackground(String... params) {
try {
String urlString = "yourUrl";
URL url = new URL(urlString);
//the variables and data you want to send by POST
String postData = "exampleID="+exampleID+"&exampleData="+exampleData;
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
OutputStream os = connection.getOutputStream();
os.write(postData.getBytes());
StringBuilder responseSB = new StringBuilder();
int result = connection.getResponseCode();
BufferedReader br;
// 401 - 422 - 403 - 500
if (result == 401 || result == 422 || result == 403 || result == 404 || result == 500){
br = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
}else {
br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
}
while ( (JSON_STRING = br.readLine()) != null)
responseSB.append(JSON_STRING+ "\n");
// Close streams
br.close();
return responseSB.toString().trim();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
#Override
protected void onPostExecute(String result) {
Log.d("Result:", result);
//send the result to interface;
response.resultPostExample(result);
}
}
2) Here is the Interface
public interface AsynkTaskRespone {
void resultPostExample(String result);
}
3) Now in the activity
public class MainActivity extends AppCompatActivity implements AsynkTaskResponse {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Start Request
RequestManager.requestPostExample requestPostExample = new RequestManager.requestPostExample(this, exampleID, exampleData);
requestPostExample.response = this;
requestPostExample.execute();
}
#Override
public void resultPostExample(String result){
//here you get the result of the asynktask
}
}
i would like to write data in an external mysql database with my android app.
this class works for that:
public class SendingData extends AppCompatActivity {
Intent intent = null;
private class LoadingDataURL extends AsyncTask<String, String, JSONArray> {
#Override
protected JSONArray doInBackground(String... params) {
URL url;
HttpURLConnection urlConnection = null;
JSONArray response = new JSONArray();
try {
url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
String responseString = readStream(urlConnection.getInputStream());
intent = new Intent(SendingData.this, Overview.class);
startActivity(intent);
response = new JSONArray(responseString);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null)
urlConnection.disconnect();
}
return response;
}
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loading_data);
String firstname = "Max";
String secondname= "Mustermann";
LoadingDataURL client = new LoadingDataURL();
client.execute("https://domain.com/index.php?"+
"fristname="+fristname+
"&secondname="+secondname);
}
}
My Problem is, that if in my strings (fristname, secondname) is an & or ? or any special characters, the entry will not be save correctly.
any ideas? :)
Use the URLEncoder class.
Try this please
String fn = URLEncoder.encode(fristname, "utf-8");
String sn = URLEncoder.encode(secondname, "utf-8");
LoadingDataURL client = new LoadingDataURL();
client.execute("https://domain.com/index.php?"+
"fristname=" + fn + "&secondname=" + sn);
Note: Don't encode the full url, just the parameter values.
I put together an RSS reader that works as-is but, I want to setup the connection to the RSS URL using HttpUrlConnection method. When I tried it, the program locked up after I clicked Read Rss button:
private class getRssFeedTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
URL rssUrl = new URL(params[0]);
HttpURLConnection urlIn = (HttpURLConnection) rssUrl.openConnection();
InputStream in = new BufferedInputStream(urlIn.getInputStream());
String line;
feed = "";
while ((line = in.toString()) != null) {
feed += line;
}
in.close();
return feed;
} catch (MalformedURLException ue) {
System.out.println("Malformed URL");
} catch (IOException ioe) {
System.out.println("The URL is unreachable");
}
return null;
}
}
This is the connection method I am stuck using which works:
private class getRssFeedTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
URL rssUrl = new URL(params[0]);
BufferedReader in = new BufferedReader(new InputStreamReader(rssUrl.openStream()));
String line;
feed = "";
while ((line = in.readLine()) != null) {
feed += line;
}
in.close();
return feed;
} catch (MalformedURLException ue) {
System.out.println("Malformed URL");
} catch (IOException ioe) {
System.out.println("The URL is unreachable");
}
return null;
}
}
Thanks for any help you can provide!
What you need to do is put it into a string I called it results. I have attached my code for the doInBackground. By adding it to a string it has a place to store the feed. And it works for the rss reader.
public String doInBackground(String... urls){
String result = "";
try{
URL url = new URL(urls[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream in = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while((line = reader.readLine()) != null){
result = result + line;
}
conn.disconnect();
}
catch(Exception e){
Log.e("ERROR Fetching ", e.toString());
}
return result;
}
The code pasted below was taken from Javadocs on HttpURLConnection.
I get the following error:
readStream(in)
...as there is no such method.
I see this same thing in the Class Overview for URLConnection at
URLConnection.getInputStream
Where is readStream? The code snippet is provided below:
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try
{
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in); <-----NO SUCH METHOD
}
finally
{
urlConnection.disconnect();
}
Try with this code:
InputStream in = address.openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder result = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
It looks like the documentation is just using readStream() to mean:
Ok, we've shown you how to get the InputStream, now your code goes in readStream()
So you should either write your own readStream() method which does whatever you wanted to do with the data in the first place.
Spring has an util class for that:
import org.springframework.util.FileCopyUtils;
InputStream is = connection.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
FileCopyUtils.copy(is, bos);
String data = new String(bos.toByteArray());
try this code
String data = "";
InputStream iStream = httpEntity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream, "utf8"));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
System.out.println(data);
a complete code for reading from a webservice in two ways
public void buttonclick(View view) {
// the name of your webservice where reactance is your method
new GetMethodDemo().execute("http://wervicename.nl/service.asmx/reactance");
}
public class GetMethodDemo extends AsyncTask<String, Void, String> {
//see also:
// https://developer.android.com/reference/java/net/HttpURLConnection.html
//writing to see: https://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html
String server_response;
#Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
server_response = readStream(urlConnection.getInputStream());
Log.v("CatalogClient", server_response);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
Log.v("bufferv ", server_response);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.e("Response", "" + server_response);
//assume there is a field with id editText
EditText editText = (EditText) findViewById(R.id.editText);
editText.setText(server_response);
}
}