call asmx web service from android - java

I have this C# working example
void Main()
{
string r = String.Format("<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"><s:Body><TrackMobileApp xmlns=\" url \" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"><device>test device</device><imei>000000</imei><ipAddress>192.168.1.1</ipAddress><timeStamp>{0}</timeStamp></TrackMobileApp></s:Body></s:Envelope>", DateTime.Now.ToString("o"));
HttpWebRequest wr = (HttpWebRequest)HttpWebRequest.Create("asmx url");
wr.ProtocolVersion = HttpVersion.Version11;
wr.Headers.Add("SOAPAction", "\"soap action url\"");
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();
}
}
}
I've tried this in android:
private class DownloadTask extends AsyncTask<String, Void, String> {
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 url");
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "text/xml;");
conn.setDoInput(true);
conn.setDoOutput(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();
}
}
}
...
}
and I'm calling it using:
new DownloadTask().execute("asmx url");
how can I attach body to that HttpURLConnection ?
or if there's something more to do tell me.. I'm beginner at java

Try this
if(body != null) {
DataOutputStream writer = new DataOutputStream(conn.getOutputStream());
byte[] data = body.toString().getBytes("UTF-8");
writer.write(data);
writer.flush();
writer.close();
}

Related

Java Bitstamp API market order File not Found

I am trying to make a post from Java to make a market order using my Bitstamp account but the following code is returning a file not found for the URL.
It may be because of CSRF but I am unsure, if anyone has had any experience with the bitstamp API that would be great.
public static void postToken() throws IOException, JSONException {
URL url = null;
String sig = encode();
try {
url = new URL("https://www.bitstamp.net/api/v2/buy/market/" + feedbackType.toLowerCase() +"usd/");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000);//5 secs
connection.setReadTimeout(5000);//5 secs
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
JSONObject cred = new JSONObject();
cred.put("key",api_key);
cred.put("signature", sig);
cred.put("nonce", nonce);
cred.put("amount", feedback);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(cred.toString());
out.flush();
out.close();
int res = connection.getResponseCode();
System.out.println(res);
InputStream is = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
while((line = br.readLine() ) != null) {
Log.d(TAG, line);
}
connection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
Error: W/System.err: java.io.FileNotFoundException: https://www.bitstamp.net/api/v2/buy/market/btcusd/

java.net.ConnectException Connection timed out: connect

I'm working with a RESTFul api in Java EE7. I'm using a #Stateless EJB with a method that I can reach by a HTTP Post request. I am trying to validate a recaptcha code in the server side, so I need to make a HTTP Post request to https://www.google.com/recaptcha/api/siteverify/ with my secret key and the google captcha response that the client sent.
The problem occurs when I try to make the request from the server. The exception is a ConnectException with message "Connection timed out: connect". I think I cannot connect to the web, but I am not sure. I am using NetBeans IDE 8.1
Here is the code:
#Stateless
#Path("sign-in")
public class SignIn
{
#POST
#Produces(MediaType.APPLICATION_JSON)
public javax.ws.rs.core.Response registerUser(String data) throws IOException, JSONException
{
JSONObject JObj = new JSONObject(data);
String gCaptchaResponse = JObj.getString("$captchaResponse");
if (!VerifyGCaptchaResponse(gCaptchaResponse))
{
//Response with error
}
//Logic to "sign-in"
//...
}
private final String urlverificacion = "https://www.google.com/recaptcha/api/siteverify/";
private boolean VerifyGCaptchaResponse(String GCResponse) throws JSONException
{
boolean res = false;
String paramSecret = "secret="+appSettings.getCaptchaSecretKey();
String paramResponse = "response="+GCResponse;
String urlparameters = paramSecret + "&" + paramResponse;
byte[] postData = urlparameters.getBytes( StandardCharsets.UTF_8 );
int postDataLength = postData.length;
HttpURLConnection connection = null;
try
{
URL url = new URL(urlverificacion);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty( "charset", "utf-8");
connection.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
//Make request
OutputStream os = connection.getOutputStream(); // <<<<<<===== Here is when the problem occurs!!!
os.write(postData);
os.flush();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
{
throw new RuntimeException("Fallo conexion : codigo de error HTTP : " + connection.getResponseCode());
}
StringBuilder builder = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader((connection.getInputStream())));
String output;
System.out.println("Respuesta del servicio .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
builder.append(output);
}
String idSicom = "0";
Integer id = 0;
JSONObject jResponse = new JSONObject(builder.toString());
if (jResponse.has("success"))
{
String success = jResponse.getString("success");
res = true;
}
else
{
}
connection.disconnect();
}
catch (java.net.ConnectException e)
{
String error = e.getMessage();
String cause = Arrays.toString(e.getStackTrace());
}
catch (IOException | RuntimeException | JSONException e)
{
String error = e.getMessage();
String cause = Arrays.toString(e.getStackTrace());
}
finally
{
}
return res;
}
}

Android GET inside a POST not working

I need to send some variables to be stored into a database, and some to be displayed in the screen in a PHP page. I did not find how to do it all together and go to the webpage to show the variables on the screen with the POST method so I am trying to do it by passing them through the URL with the GET method.
POST method is working fine, and the variables are stored in the database, but after this, the app does not go to the webpage and shows another variable on the screen. Here is my code:
public class Main3Activity extends AppCompatActivity {
public String precio;
URL url;
Button b1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
b1 = (Button) findViewById(R.id.button_pago);
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
new SendPostRequest().execute();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public void getMethod() throws IOException {
url = new URL("https://www.webpage.com/login_app.php?username=" + precio );
}
public class SendPostRequest extends AsyncTask<String, Void, String> {
protected void onPreExecute(){}
protected String doInBackground(String... arg0) {
try {
URL url = new URL("https://www.webpage.com/login_app.php"); // here is your URL path
JSONObject postDataParams = new JSONObject();
postDataParams.put("precio", "1€");
Log.e("params",postDataParams.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in=new BufferedReader(new
InputStreamReader(
conn.getInputStream()));
StringBuffer sb = new StringBuffer("Success");
String line="";
getMethod();
while((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
}
else {
return new String("false : "+responseCode);
}
}
catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(), result,
Toast.LENGTH_LONG).show();
}
}
public String getPostDataString(JSONObject params) throws Exception {
StringBuilder result = new StringBuilder();
boolean first = true;
Iterator<String> itr = params.keys();
while(itr.hasNext()){
String key= itr.next();
Object value = params.get(key);
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(key, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value.toString(), "UTF-8"));
}
return result.toString();
}
Do somebody have an idea to solve it?
Thank you for your time.
EDIT:
Thanks to #user6749691, now I have got the following script to do the GET method:
private void openConnection(String method, URL url) {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod(method);
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
}
public URL getMethod() throws IOException {
return new URL("https://www.webpage.com/login_app.php?username=" + precio );
}
And then I call the function openConnection("GET", getMethod()); in the following lines of the 'SendPostRequest' class:
StringBuffer sb = new StringBuffer("Success");
String line="";
openConnection("GET", getMethod());
while((line = in.readLine()) != null) {
.
.
.
But I am getting Unhandled Exception in 'url.openConnection()' and in 'conn.setRequestMethod(method);'
First of all, try to use some great networking library as Retrofit or Volley.
Inside your getMethod you are just creating URL object. You need to open new URL connection.
Something like this:
private void openConnection(String method, URL url) {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod(method);
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
}
and then :
public URL getMethod() throws IOException {
return new URL("https://www.webpage.com/login_app.php?username=" + precio );
}
openConnection("GET", getMethod());
Try the following:
private String openConnection(String requestMethod, String link) {
URL url;
StringBuilder sb = new StringBuilder();
sb.append("");
try {
BufferedReader reader;
if(requestMethod == "GET"){
url = new URL(link);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(requestMethod);
conn.setUseCaches(false);
conn.setDoInput(true);
conn.connect();
int STATUS = conn.getResponseCode();
Log.e(TAG, "ResponseCode: " + STATUS);
if(STATUS == 200 || STATUS == 201)
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
else
reader = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "");
}
}
else {
url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
jsonSend.put("your_parameter", "parameter_value");
String output = jsonSend.toString();
OutputStreamWriter wr = new OutputStreamWriter(
conn.getOutputStream());
wr.write(output);
wr.flush();
reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "");
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return sb.toString();
}
For the best practice, try to use the Retrofit

How do I change this code to make use of HttpURLConnection instead of httpClient

I know the HttpClient is depreceted and their alot of questions about an alternative. I have seen those questions and even read the documentation for HttpURLConnection. For the love of I cannot seem to get my code working with HttpUrlConnection. Are there any suggestions. Here is the code.
#Override
protected Void doInBackground(Void... params) {
ContentValues dataToSend =new ContentValues();
dataToSend.put("name", user.name);
dataToSend.put("uersname", user.username);
dataToSend.put("password", user.password);
dataToSend.put("age", user.age + "");
// URL myUrl = new URL("http://192.168.182.15/connection.php");
// HttpURLConnection conn = (HttpURLConnection) myUrl.openConnection();
HttpParams httpRequestParams = getHttpRequestParams();
HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost(SERVER_ADDRESS
+ "Register.php");
try {
post.setEntity(new UrlEncodedFormEntity(dataToSend));
client.execute(post);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private HttpParams getHttpRequestParams() {
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams,
CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpRequestParams,
CONNECTION_TIMEOUT);
return httpRequestParams;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
progressDialog.dismiss();
userCallBack.done(null);
}
Use this JSONParser class this is easy to use.
JSONParser.java
public class JSONParser {
public JSONParser() {
}
public String makeBufferCall(String serviceUrl) {
Boolean registered = false;
StringBuffer response = new StringBuffer();
URL url = null;
HttpURLConnection conn = null;
try {
url = new URL(serviceUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(30000);
conn.setDoOutput(false);
conn.setUseCaches(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
int status = conn.getResponseCode();
if (status != 200) {
throw new IOException("Post failed with error code " + status);
}
registered = true;
// Get Response
InputStream is = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
}
rd.close();
} catch (Exception e) {
e.printStackTrace();
//ErrorLogger.writeLog(claimNo, "Error Msg : "+e.getMessage()+"..."+ErrorLogger.StackTraceToString(e), "sendSyncService Failed");
//response.append("Error");
}
Log.v("Response:", response.toString());
return response.toString();
}
}
And use this class in AsyncTask using just calling the method. So don't need to whole code write in every time.
#Override
protected Void doInBackground(Void... params) {
// Locate the Offer_POJO Class
property_data = new ArrayList<Contract_POJO>();
// Create an array to populate the spinner
property = new ArrayList<String>();
JSONParser call = new JSONParser();
jsonstr = call.makeBufferCall(url_property);
Log.d("Response: ", "> " + jsonstr);
return null;
}
I am not run this code but I think it will work fine..
#Override
protected Void doInBackground(Void... params) {
ContentValues dataToSend =new ContentValues();
dataToSend.put("name", user.name);
dataToSend.put("uersname", user.username);
dataToSend.put("password", user.password);
dataToSend.put("age", user.age + "");
// URL myUrl = new URL("http://192.168.182.15/connection.php");
// HttpURLConnection conn = (HttpURLConnection) myUrl.openConnection();
try {
URL myUrl = new URL("http://192.168.182.15/connection.php");
HttpURLConnection conn = (HttpURLConnection) myUrl.openConnection();
HttpClient client = new HttpClient();
HttpMethod post = new PostMethod("SERVER_ADDRESS"+ "Register.php");
post.setQueryString(new UrlEncodedFormEntity(dataToSend));
client.executeMethod(post);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

How to stream a JSON object to a HttpURLConnection POST request

I can not see what is wrong with this code:
JSONObject msg; //passed in as a parameter to this method
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setDoInput(true);
httpCon.setUseCaches(false);
httpCon.setRequestProperty( "Content-Type", "application/json" );
httpCon.setRequestProperty("Accept", "application/json");
httpCon.setRequestMethod("POST");
OutputStream os = httpCon.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
msg.write(osw);
osw.flush();
osw.close();
os.close(); //probably overkill
On the server, I am getting no post content at all, a zero length string.
Try
...
httpCon.setRequestMethod("POST");
httpCon.connect(); // Note the connect() here
...
OutputStream os = httpCon.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
...
osw.write(msg.toString());
osw.flush();
osw.close();
to send data.
to retrieve data try:
BufferedReader br = new BufferedReader(new InputStreamReader( httpCon.getInputStream(),"utf-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
System.out.println(""+sb.toString());
public String sendHTTPData(String urlpath, JSONObject json) {
HttpURLConnection connection = null;
try {
URL url=new URL(urlpath);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
OutputStreamWriter streamWriter = new OutputStreamWriter(connection.getOutputStream());
streamWriter.write(json.toString());
streamWriter.flush();
StringBuilder stringBuilder = new StringBuilder();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK){
InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(streamReader);
String response = null;
while ((response = bufferedReader.readLine()) != null) {
stringBuilder.append(response + "\n");
}
bufferedReader.close();
Log.d("test", stringBuilder.toString());
return stringBuilder.toString();
} else {
Log.e("test", connection.getResponseMessage());
return null;
}
} catch (Exception exception){
Log.e("test", exception.toString());
return null;
} finally {
if (connection != null){
connection.disconnect();
}
}
}`
call this methopd in doitbackground in asynctask
HttpURLConnection is cumbersome to use. With DavidWebb, a tiny wrapper around HttpURLConnection, you can write it like this:
JSONObject msg; //passed in as a parameter to this method
Webb webb = Webb.create();
JSONObject result = webb.post("http://my-url/path/to/res")
.useCaches(false)
.body(msg)
.ensureSuccess()
.asJsonObject()
.getBody();
If you don't like it, there is a list of alternative libraries on the link provided.
Why should we all write the same boilerplate code every day? BTW the code above is more readable and less error-prone. HttpURLConnection has an awful interface. This has to be wrapped!
Follow this example:
public static PricesResponse getResponse(EventRequestRaw request) {
// String urlParameters = "param1=a&param2=b&param3=c";
String urlParameters = Piping.serialize(request);
HttpURLConnection conn = RestClient.getPOSTConnection(endPoint, urlParameters);
PricesResponse response = null;
try {
// POST
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(urlParameters);
writer.flush();
// RESPONSE
BufferedReader reader = new BufferedReader(new InputStreamReader((conn.getInputStream()), StandardCharsets.UTF_8));
String json = Buffering.getString(reader);
response = (PricesResponse) Piping.deserialize(json, PricesResponse.class);
writer.close();
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
conn.disconnect();
System.out.println("PricesClient: " + response.toString());
return response;
}
public static HttpURLConnection getPOSTConnection(String endPoint, String urlParameters) {
return RestClient.getConnection(endPoint, "POST", urlParameters);
}
public static HttpURLConnection getConnection(String endPoint, String method, String urlParameters) {
System.out.println("ENDPOINT " + endPoint + " METHOD " + method);
HttpURLConnection conn = null;
try {
URL url = new URL(endPoint);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(method);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "text/plain");
} catch (IOException e) {
e.printStackTrace();
}
return conn;
}
this without json String post data to server
class PostLogin extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
String response = null;
Uri.Builder builder= new Uri.Builder().appendQueryParameter("username","amit").appendQueryParameter("password", "amit");
String parm=builder.build().getEncodedQuery();
try
{
response = postData("your url here/",parm);
}catch (Exception e)
{
e.printStackTrace();
}
Log.d("test", "response string is:" + response);
return response;
}
}
private String postData(String path, String param)throws IOException {
StringBuffer response = null;
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
// connection.setRequestProperty("Content-Type", "application/json");
// connection.setRequestProperty("Accept", "application/json");
OutputStream out = connection.getOutputStream();
out.write(param.getBytes());
out.flush();
out.close();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
response = new StringBuffer();
while ((line = br.readLine()) != null) {
response.append(line);
}
br.close();
}
return response.toString();
}

Categories

Resources