I am trying to call a rest web api that is hosted in a server.But i am getting
java.net.ConnectException: Failed to connect to /10...***:45.
It is POST method,passing JSON as parameter.
CommonAsyncTask cat=new CommonAsyncTask(MainActivity.this,jsonParam,1);
cat.delegate = MainActivity.this;
cat.execute(getResources().getString(R.string.url));
I am able open connection but error occurs when i try to getOutputstream on HttpURLConnection object.
Is this the correct way to call a web api written in asp.net from android?
if yes ,please help me fix this error.
public class CommonAsyncTask extends AsyncTask<String, Integer, String> {
JSONObject params;
// private ProgressDialog progressDialog = null;
Context mContext;
public AsyncResponse delegate = null;
public static final int POST_TASK = 1;
public static final int GET_TASK = 2;
private int taskType;
private ProgressDialog progressDialog = null;
InputStream is;
public CommonAsyncTask(Context mContext, JSONObject params, int taskType) {
this.mContext = mContext;
this.params = params;
this.taskType = taskType;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
/*progressDialog = ProgressDialog.show(mContext, "Please wait",
"Connecting");
progressDialog.setCancelable(true);*/
}
#Override
protected String doInBackground(String... urls) {
// TODO Auto-generated method stub
String result = "";
try {
/*
* Communication with Webservice
*/
switch (taskType) {
case POST_TASK:
Log.d("TAG:","POSTT");
URL url = new URL(urls[0]);
Log.d("b4 con","here");
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
Log.d("after con.open","here");
conn.setRequestMethod("POST");
Log.d("seting post","here");
conn.setDoOutput(true);
Log.d("DOOUTPUT-true","here");
conn.setDoInput(true);
Log.d("DOinputPUT-true","here");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
Log.d("contenttype-json","here");
DataOutputStream wr = new DataOutputStream(conn.getOutputStream ());
Log.d("data outputstream","here");
wr.writeBytes(params.toString());
wr.flush();
wr.close();
Log.d("b4","conn.connect");
conn.connect();
int responsePostCode = conn.getResponseCode();
if(responsePostCode>=400){
is = conn.getErrorStream();
}
else{
is=conn.getInputStream();
}
BufferedReader in = new BufferedReader(new InputStreamReader(
is));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
result = response.toString();
Log.d("LWCP", "Response: " + result);
break;
case GET_TASK:
/*
* String query = String.format("mobile=%s",
* URLEncoder.encode(cid, "utf-8"));
*/
URL obj = new URL(urls[0]);
// URL obj = new URL(url[0] + "?mobile=" + cid);
HttpURLConnection con = (HttpURLConnection) obj
.openConnection();
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
Log.d("Sending'GET'request to:", urls + "");
Log.d("Response Code : ", responseCode + "");
Log.d("url-",urls[0]);
if(responseCode>=400){
is = con.getErrorStream();
}
else{
is=con.getInputStream();
}
BufferedReader inReader = new BufferedReader(
new InputStreamReader(is));
String inLine;
StringBuffer responseBuffer = new StringBuffer();
while ((inLine = inReader.readLine()) != null) {
responseBuffer.append(inLine);
}
inReader.close();
con.connect();
result = responseBuffer.toString();
Log.d("LWCP", "Response: " + result);
break;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return result;
}
protected void onPostExecute(String result) {
//progressDialog.dismiss();
delegate.processFinish(result);
}
}
sharing my log
D/TAG:: POSTT
D/b4 con: here
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/after con.open: here
D/seting post: here
D/DOOUTPUT-true: here
D/DOinputPUT-true: here
D/contenttype-json: here
W/System.err: java.net.ConnectException: Failed to connect to /10.142.173.112:45
at com.android.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:143)
at com.android.okhttp.internal.io.RealConnection.connect(RealConnection.java:112)
at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:184)
at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:126)
at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:95)
W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:281)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:224)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:461)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:127)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:258)
at com.example.restcall.CommonAsyncTask.doInBackground(CommonAsyncTask.java:78)
at com.example.restcall.CommonAsyncTask.doInBackground(CommonAsyncTask.java:19)
at android.os.AsyncTask$2.call(AsyncTask.java:333)
W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
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 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();
}
}
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 am trying to successfully send data across from an android app to a php web app and display that data and save into a mysql database. However i don't get an exception or anything just the data i send across does not get received on the server end. My code is below:
public void onClick(View view) {
String text = "None";
switch (view.getId()) {
case R.id.btnOne:
send();
text = "Response Submitted";
break;
case R.id.btnTwo:
text = "Two";
break;
case R.id.btnThree:
text = "Three";
break;
case R.id.btnFour:
text = "Four";
break;
}
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
}
private void send() {
URL a = null;
try {
a = new URL("http://cce.swlgroup.com/json.php/");
} catch (Exception exception) {
exception.printStackTrace();
}
new URLTestTask().execute(a);
}
private class URLTestTask extends AsyncTask<URL, Integer, Void> {
#Override
protected void doInBackground(URL... urls) {
HttpURLConnection conn = null;
BufferedReader reader = null;
try {
URL url = new URL("http://cce.swlgroup.com/json.php/");
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
Log.e("", "" + conn.getResponseMessage());
conn.connect();
JSONObject obj = new JSONObject();
obj.put("Marge","Simpson");
HttpClient client = new DefaultHttpClient();
HttpGet post = new HttpGet(url.toURI());
post.setEntity(new ByteArrayEntity(obj.toString().getBytes("UTF8")));
post.setHeader("json",obj.toString());
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String responseBody = client.execute(post,
responseHandler);
HttpEntity ent = post.getEntity();
InputStream stream = ent.getContent();
String result = RestClient.convertStreamToString(stream);
BufferedReader red = new BufferedReader(new InputStreamReader(ent.getContent()));
String line;
StringBuilder lb = new StringBuilder();
while((line = red.readLine()) != null){
lb.append(red);
}
red.close();
Log.i("Read from server", result);
} catch (Exception e){
e.printStackTrace();
}finally {
if (conn != null)
conn.disconnect();
try{
if (reader != null)
reader.close();
} catch (Exception e){
e.printStackTrace();
}
}
return null;
}
}
my php code is below to get data and display:
$json = file_get_contents('php://input');
$obj = json_decode($json);
var_dump($obj);
var_dump($_POST);
var_dump($_GET);
HttpURLConnection conn = null;
BufferedReader reader = null;
try {
URL url = new URL("http://10.0.2.2/json.php/");
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
Log.e("", "" + conn.getResponseMessage());
conn.connect();
JSONObject obj = new JSONObject();
obj.put("Marge","Simpson");
HttpClient client = new DefaultHttpClient();
StringBuilder pat = new StringBuilder();
HttpGet post = new HttpGet(url.toURI());
post.setEntity(new ByteArrayEntity(obj.toString().getBytes("UTF8")));
post.setHeader("json", obj.toString());
post.setHeader("Content-Type", "application/json");
post.setHeader("accept-encoding","gzip, deflate");
post.setHeader("accept-language","en-US,en;q=0.8");
post.setHeader("FormData",obj.toString());
HttpResponse lazy = client.execute(post);
HttpEntity ent = lazy.getEntity();
String lb = EntityUtils.toString(ent);
pat.append(lb);
Log.i("Read from server", pat.toString());
} catch (Exception e){
e.printStackTrace();
}finally {
if (conn != null)
conn.disconnect();
try{
if (reader != null)
reader.close();
} catch (Exception e){
e.printStackTrace();
}
}
return null;
I made the change in accordance with that code but it doesnt seem to send a result across.
I'm trying to post HTTP from android. If I'll request using that C# code in LINQPAD it works
void Main()
{
string r = String.Format(#"<s:Body><TrackMobileApp xmlns=""soap action url"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance""><device>test</device><imei>test</imei><ipAddress>127.0.0.1</ipAddress><timeStamp>2016-02-17T17:32:00.5147663+04:00</timeStamp></TrackMobileApp></s:Body>", DateTime.Now.ToString("o"));
HttpWebRequest wr = (HttpWebRequest)HttpWebRequest.Create("URL.asmx");
wr.ProtocolVersion = HttpVersion.Version11;
wr.Headers.Add("SOAPAction", "soap action");
wr.Method = "POST";
wr.ContentType = "text/xml;charset=utf-8";
using (StreamWriter sw = new StreamWriter(wr.GetRequestStream()))
{
sw.Write(r);
}
HttpWebResponse rs = (HttpWebResponse)wr.GetResponse();
if (rs.StatusCode == HttpStatusCode.OK)
{
XmlDocument xd = new XmlDocument();
using (StreamReader sr = new StreamReader(rs.GetResponseStream()))
{
xd.LoadXml(sr.ReadToEnd());
xd.InnerXml.Dump();
}
}
}
But from android it gives me http 415. What's wrong?
I have this in onCreate
new DownloadTask().execute("URL.asmx");
and my methods are:
private class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
//do your request in here so that you don't interrupt the UI thread
try {
return downloadContent(params[0]);
} catch (IOException e) {
return "Unable to retrieve data. URL may be invalid.";
}
}
#Override
protected void onPostExecute(String result) {
//Here you are done with the task
}
}
private String downloadContent(String myurl) throws IOException {
InputStream is = null;
int length = 500;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestProperty("SOAPAction", "soap action");
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/xml");
conn.setDoInput(true);
conn.connect();
int response = conn.getResponseCode();
Log.d(TAG, "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = convertInputStreamToString(is, length);
return contentAsString;
} finally {
if (is != null) {
is.close();
}
}
}
public String convertInputStreamToString(InputStream stream, int length) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[length];
reader.read(buffer);
return new String(buffer);
}