I have a web service that returns an ArrayList of object Home... this is my class Home:
import java.io.FileNotFoundException;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
public class Home implements Serializable {
public void setPercorso(String percorso) {
this.percorso = percorso;
}
public String getPercorso() {
return percorso;
}
public void setNomignolo(String nomignolo) {
this.nomignolo = nomignolo;
}
public void setNome(String nome) {
this.nome = nome;
}
public void setUtente(String utente) {
this.utente = utente;
}
public void setFamiglia(String famiglia) {
this.famiglia = famiglia;
}
public void setFoto(byte[] foto) {
this.foto = foto;
}
public String getNomignolo() {
return nomignolo;
}
public String getNome() {
return nome;
}
public String getUtente() {
return utente;
}
public String getFamiglia() {
return famiglia;
}
public byte[] getFoto() {
return foto;
}
public Home(String nomignolo, String nome, String utente, String famiglia, byte[] foto, String percorso) {
this.nomignolo = nomignolo;
this.nome = nome;
this.utente = utente;
this.famiglia = famiglia;
this.foto = foto;
this.percorso = percorso;
}
public Home() {
}
private String nomignolo;
private String nome;
private String utente;
private String famiglia;
private byte[] foto;
private String percorso;
public ArrayList<Home> caricaH() throws SQLException, ClassNotFoundException, MyException, FileNotFoundException {
ArrayList<Home> list = new ArrayList<Home>();
list= HomeDAO.caricaHome(this);
return list;
}
}
In the Android part i receive data in this way:
// other code bla bla bla...
public static ArrayList<Home> invokeHomeWS(String userName, String webMethName) {
boolean homeStatus = false;
ArrayList<Home> list = new ArrayList<Home>();
SoapObject request = new SoapObject(NAMESPACE, webMethName);
PropertyInfo unamePI = new PropertyInfo();
// Set Username
unamePI.setName("username");
// Set Value
unamePI.setValue(userName);
// Set dataType
unamePI.setType(String.class);
// Add the property to request object
request.addProperty(unamePI);
// Create envelope
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
// Set output SOAP object
envelope.setOutputSoapObject(request);
// Create HTTP call object
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
// Invoke web service
androidHttpTransport.call(SOAP_ACTION + webMethName, envelope);
// Get the response
java.util.Vector<SoapObject> rs = (java.util.Vector<SoapObject>) envelope.getResponse();
for(SoapObject cs : rs){
Home item = new Home();
item.setNomignolo(cs.getPropertyAsString("nomignolo"));
item.setUtente(cs.getPropertyAsString("utente"));
item.setNome(cs.getPropertyAsString("nome"));
item.setPercorso(cs.getPropertyAsString("percorso"));
item.setFoto((byte[])cs.getProperty("foto"));
item.setFamiglia(cs.getPropertyAsString("famiglia"));
list.add(item);
}
} catch (Exception e) {
//Assign Error Status true in static variable 'errored'
HomeActivity.errored = true;
e.printStackTrace();
}
return list;
}
everything works except
item.setFoto((byte[])cs.getProperty("foto"));...
it generates an error:
W/System.err﹕ java.lang.ClassCastException:
org.ksoap2.serialization.SoapPrimitive cannot be cast to byte[].
So my question is: how i can obtain the byte array from the SoapObject?
if it is return String, you can convert it to byte[] as below. try this out.
byte[] b = string.getBytes();
Just try this
byte[] bitmapdata = blob.toByteArray();
and if bitmap data is the byte array then getting bitmap goes like this
Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata , 0, bitmapdata .length);
Hope this help.
Related
I try to get xml data then I parse it to JSON, I use OkHttp as a connection. I managed to get data from LOG but I can't display it in my RecyclerView, when I LOG to adapter and the result is size 0
I set the response to the model and sharedpreference
The point of the problem is that I just don't understand how to take the response from the presenter then I set it to the adapter in the main Fragment.
public class ParentCategories {
#SerializedName("idkategori")
#Expose
private String idkategori;
#SerializedName("namakategori")
#Expose
private String namakategori;
#SerializedName("fileicon")
#Expose
private String fileicon;
#SerializedName("subkategori")
#Expose
private SubCategories subkategori;
public ParentCategories(Parcel in) {
this.idkategori = in.readString();
this.namakategori = in.readString();
this.fileicon = in.readString();
}
public ParentCategories() {
}
public String getIdkategori() {
return idkategori;
}
public void setIdkategori(String idkategori) {
this.idkategori = idkategori;
}
public String getNamakategori() {
return namakategori;
}
public void setNamakategori(String namakategori) {
this.namakategori = namakategori;
}
public String getFileicon() {
return fileicon;
}
public void setFileicon(String fileicon) {
this.fileicon = fileicon;
}
public SubCategories getSubkategori() {
return subkategori;
}
public void setSubkategori(SubCategories subkategori) {
this.subkategori = subkategori;
}
}
public class CategoriesPresenter {
....
public void onResponse(Call call, Response response) throws IOException {
String mMessage = response.body().string();
JSONObject jsonObj = null;
try {
jsonObj = XML.toJSONObject(mMessage);
JSONObject jsonObject = new JSONObject(jsonObj.toString());
JSONObject object = jsonObject.getJSONObject("posh");
String attr2 = object.getString("resultcode");
com.davestpay.apphdi.helper.Log.d("hasil", String.valueOf(object));
if (attr2.equalsIgnoreCase("0000")) {
String idAgen = object.getString("idagen");
int jumlahKategori = object.getInt("jumlahkategori");
JSONArray category = object.getJSONArray("kategori");
List<ParentCategories> parentCategories = new ArrayList<ParentCategories>();
for (int i = 0; i < category.length(); i++) {
ParentCategories categories = new ParentCategories();
JSONObject c = category.getJSONObject(i);
Log.d(TAG, "onResponseC: "+c);
String idKategori = c.getString("idkategori");
String namaKategori = c.getString("namakategori");
Log.d(TAG, "onResponseNamaKategori: "+namaKategori);
String fileIcon = c.getString("fileicon");
JSONObject subCategories = c.getJSONObject("subkategori");
JSONArray subCategory = subCategories.getJSONArray("kategori2");
Log.d(TAG, "onResponseSubCategories: "+subCategory);
for (int subCatPosition = 0; subCatPosition < subCategory.length(); subCatPosition++) {
SecondCategories secondCategories = new SecondCategories();
List<SecondCategories> listSecondCategories = new ArrayList<>();
JSONObject sc = subCategory.getJSONObject(subCatPosition);
String secIdKategori = sc.getString("idkategori");
String secNamaKategori = sc.getString("namakategori");
String secFileIcon = sc.getString("fileicon");
secondCategories.setIdkategori(secIdKategori);
secondCategories.setNamakategori(secNamaKategori);
secondCategories.setFileicon(secFileIcon);
listSecondCategories.add(secondCategories);
}
categories.setIdkategori(idKategori);
categories.setNamakategori(namaKategori);
categories.setFileicon(fileIcon);
parentCategories.add(categories);
Log.d(TAG, "onResponseFinalCategories: "+parentCategories);
}
iCategories.onSuccessCategories(parentCategories);
preferenceHelper.clear(PreferenceHelper.CATEGORIES);
preferenceHelper.putList(PreferenceHelper.CATEGORIES, parentCategories);
} else {
Log.d(TAG, "onResponse: ");
}
} catch (JSONException e) {
com.davestpay.apphdi.helper.Log.e("JSON exception", e.getMessage());
e.printStackTrace();
}
}
}
private void getInit() {
if (preferenceHelper != null) {
idAgen = preferenceHelper.getString(PreferenceHelper.ID_AGEN);
namaAgen = preferenceHelper.getString(PreferenceHelper.NAMA_AGEN);
password = preferenceHelper.getString(PreferenceHelper.PASSWORD);
categories = preferenceHelper.getList(PreferenceHelper.CATEGORIES, ParentCategories[].class);
}
authPresenter = new AuthPresenter(getContext());
presenter = new CategoriesPresenter();
presenter.setBaseView(this);
presenter.onCreate(getContext());
if (authPresenter.isLoggedIn()) {
// kategori.setText(categories.toString());
presenter.getCategories(idAgen, password, counter);
}
kategori = mView.findViewById(R.id.kategori);
categories = new ArrayList<>();
rvMain = mView.findViewById(R.id.rv_categories);
adapter = new CategoriesListViewAdapter(getContext(), categories);
layoutManager = new LinearLayoutManager(getdActivity());
adapter.notifyDataSetChanged();
rvMain.setLayoutManager(layoutManager);
rvMain.setAdapter(adapter);
}
This is the problem.
categories = new ArrayList<>();
Here, you are initialising categories to new ArrayList<>(); It is like you are creating a new arraylist.
Just remove this line.
I want to parse a JSON object from an endpoint (this one here: https://api.coinmarketcap.com/v1/ticker/bitcoin/) and store the value in a variable at a specific attribute, which in this case is the name.
This the ERROR i get:
java.lang.IllegalStateException: Expected a name but was STRING...
AsyncTask.execute(new Runnable() {
#Override
public void run() {
// All your networking logic
// should be here
try {
String u = "https://api.coinmarketcap.com/v1/ticker/bitcoin";
URL coinMarketCapApi = new URL(u);
HttpsURLConnection myConnection = (HttpsURLConnection) coinMarketCapApi.openConnection();
myConnection.setRequestProperty("User-Agent", "my-rest-app-v0.1");
if (myConnection.getResponseCode() == 200) {
// Success
InputStream responseBody = myConnection.getInputStream();
InputStreamReader responseBodyReader =
new InputStreamReader(responseBody, "UTF-8");
JsonReader jsonReader = new JsonReader(responseBodyReader);
jsonReader.beginArray();
while (jsonReader.hasNext()) {
String key = jsonReader.nextName();
if (key.equals("name")) {
String value = jsonReader.nextName();
break; // Break out of the loop
} else {
jsonReader.skipValue();
}
}
jsonReader.close();
myConnection.disconnect();
} else {
// Error handling code goes here
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
you can convert the InputStream to String and then Create JSONArray from that string. like
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();
JSONArray jsonarray = new JSONArray(theString);
This way you don't have to manually construct the array.
Use this depandency for JSONArray
https://mvnrepository.com/artifact/org.json/json
You can fix the problem using gson.
https://github.com/google/gson
com.google.gson.stream.JsonReader jsonReader =
new com.google.gson.stream.JsonReader(new InputStreamReader(responseBody));
ArrayList<Coin> coins = new Gson().fromJson(jsonReader, Coin.class);
coins.forEach(coin -> System.out.println(coin.name));
public class Coin{
private String id;
private String name;
private String symbol;
private int rank;
#SerializedName("price_usd")
private double priceUsd;
...........
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getSymbol() {
return symbol;
}
public int getRank() {
return rank;
}
public double getPriceUsd() {
return priceUsd;
}
..........
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Iam trying to make login activity
I got a problem. My setter doesnt work, i dont know why?
I have 3 classes.
1st one is Data with server data and getters and setters
public class Data{
String addressesURL = "/DataSnap/rest/TServerMethods1/LookupCustomers";
String articlesURL = "/DataSnap/rest/TServerMethods1/LookupArticle";
String invoicesURL = "/DataSnap/rest/TServerMethods1/LookupInvoice";
String invoicesDetailsURL = "/DataSnap/rest/TServerMethods1/LookupInvoicePos";
String invoicesDetailsAddressesURL = "/DataSnap/rest/TServerMethods1/LookupInvoiceAddress";
String ordersURL = "/DataSnap/rest/TServerMethods1/LookupOrders";
String ordersDetailsURL = "/DataSnap/rest/TServerMethods1/LookupOrdersPos";
String ordersDetailsAddressesURL = "/DataSnap/rest/TServerMethods1/LookupOrdersAddress";
public String serverURL;
//String serverURL = "http://10.10.10.75:8081";
String username = "admin";
String password = "admin";
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAddressesURL() {
return addressesURL;
}
public void setAddressesURL(String addressesURL) {
this.addressesURL = addressesURL;
}
public String getArticlesURL() {
return articlesURL;
}
public void setArticlesURL(String articlesURL) {
this.articlesURL = articlesURL;
}
public String getInvoicesURL() {
return invoicesURL;
}
public void setInvoicesURL(String invoicesURL) {
this.invoicesURL = invoicesURL;
}
public String getInvoicesDetailsURL() {
return invoicesDetailsURL;
}
public void setInvoicesDetailsURL(String invoicesDetailsURL) {
this.invoicesDetailsURL = invoicesDetailsURL;
}
public String getInvoicesDetailsAddressesURL() {
return invoicesDetailsAddressesURL;
}
public void setInvoicesDetailsAddressesURL(String invoicesDetailsAddressesURL) {
this.invoicesDetailsAddressesURL = invoicesDetailsAddressesURL;
}
public String getOrdersURL() {
return ordersURL;
}
public void setOrdersURL(String ordersURL) {
this.ordersURL = ordersURL;
}
public String getOrdersDetailsURL() {
return ordersDetailsURL;
}
public void setOrdersDetailsURL(String ordersDetailsURL) {
this.ordersDetailsURL = ordersDetailsURL;
}
public String getOrdersDetailsAddressesURL() {
return ordersDetailsAddressesURL;
}
public void setOrdersDetailsAddressesURL(String ordersDetailsAddressesURL) {
this.ordersDetailsAddressesURL = ordersDetailsAddressesURL;
}
public String getServerURL() {
return serverURL;
}
public void setServerURL(String serverURL) {
this.serverURL = serverURL;
}}
2nd one is where I start my login Activity
public class Settings extends AppCompatActivity {
//declarations
//Edittext fields for username , server, password & port information
EditText edtIpurl, edtPort, edtUsername, edtPassword;
//Textviews that can be clicked
TextView databaseDel, databaseRef, magnumgmbh, contact, support;
//imagebuttons for bottom menu
ImageButton contacts, articles, invoices, orders;
//string for server URL
//String sURL = "http://";
Thread newSettingsThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
setTitle("Settings");
newSettingsThread = new Thread(){
public void run(){
runOnUiThread(new Runnable() {
#Override
public void run() {
String serverURL = "http://rest.magnumgmbh.de";
//edtIpurl = (EditText)findViewById(R.id.edtIpurl);
Data newD = new Data();
newD.setServerURL(serverURL);
}
});
}
};
newSettingsThread.start();
//start activitys if bottom buttons clicked
contacts = (ImageButton) findViewById(R.id.contacts);
//articles activity start
contacts.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//start activity addresses
Intent startAddresses = new Intent(Settings.this, Addresses.class);
startActivity(startAddresses);
}
});
}}
And the next one is where i try to get my new serverURL
public class Address extends AppCompatActivity{
Thread newAddressThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addresses);
//set activity name
setTitle("Addresses");
//new thread for network operations
newAddressesThread = new Thread() {
public void run() {
//make text from json
jsonText = new StringBuilder();
try {
String str;
Data newData = new Data();
//json dates url
String addressesURL = newData.getAddressesURL();
String serverUrl = newData.getServerURL();
String username = newData.getUsername();
String password = newData.getPassword();
URL url = new URL(serverUrl + addressesURL);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//String encoded = Base64.encode("admin:admin");
String encoded = Base64.encodeToString((username+":"+password).getBytes("UTF-8"), Base64.NO_WRAP);
urlConnection.setRequestProperty("Authorization", "Basic " + encoded);
//check http status code
try {
int statusCode = urlConnection.getResponseCode();
System.out.println(statusCode);
} catch (IOException e) {
}
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
while ((str = in.readLine()) != null) {
jsonText.append(str);
}
//cast stringbuilder to string
addressesJsonStr = jsonText.toString();
//close IOstream
in.close();
} catch (MalformedURLException e1) {
System.out.println(e1.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
};
//start thread
newAddressesThread.start();
}}
Hier in the third one by serverURL I got null and it thow me an exeption "Protocol not found: null/DataSnap/rest/TServerMethods1/LookupCustomers" so that is my problem.
What do I wrong?
you are creating a new Object in the third class, so the url has the initilize value because the url you've setted in the second class is stored in another object.
If you want that all Objects of Type Data have the same adress, make the variable static otherwise you have to access the object you have created in the second class in the third class.
First made a WebService Using axis2, which has a connection class with the database, and the class with pedidosDAO with CRUD. Using SoupUI can perform the call of methods. So far so good, I created an android app to consume these services, however this giving error when showing the data of the bank in a ListView, when I run appears (unfortunately XsaladaTeste has stopped), I had already done before and had worked but now I have been going on since time I'm not getting my logcat this buggy and not showing this log. What am I doing wrong?
PedidosXsaladaBusca.java
package com.example.xsaladateste;
public class PedidosXsaladaBusca {
private int id_pedidos;
private String informacao_adicionais;
private int mesa;
private String nome_sobrenome_cliente;
private String nome_xsalada;
private double total_a_pagar;
PedidosXsaladaBusca() {
}
PedidosXsaladaBusca(int id_pedidos, String informacao_adicionais, int mesa, String nome_sobrenome_cliente,
String nome_xsalada, double total_a_pagar) {
this.id_pedidos = id_pedidos;
this.informacao_adicionais = informacao_adicionais;
this.mesa = mesa;
this.nome_sobrenome_cliente = nome_sobrenome_cliente;
this.nome_xsalada = nome_xsalada;
this.total_a_pagar = total_a_pagar;
}
public int getId_pedidos() {
return id_pedidos;
}
public void setId_pedidos(int id_pedidos) {
this.id_pedidos = id_pedidos;
}
public String getNome_sobrenome_cliente() {
return nome_sobrenome_cliente;
}
public void setNome_sobrenome_cliente(String nome_sobrenome_cliente) {
this.nome_sobrenome_cliente = nome_sobrenome_cliente;
}
public int getMesa() {
return mesa;
}
public void setMesa(int mesa) {
this.mesa = mesa;
}
public String getInformacao_adicionais() {
return informacao_adicionais;
}
public void setInformacao_adicionais(String informacao_adicionais) {
this.informacao_adicionais = informacao_adicionais;
}
public double getTotal_a_pagar() {
return total_a_pagar;
}
public void setTotal_a_pagar(double total_a_pagar) {
this.total_a_pagar = total_a_pagar;
}
public String getNome_xsalada() {
return nome_xsalada;
}
public void setNome_xsalada(String nome_xsalada) {
this.nome_xsalada = nome_xsalada;
}
#Override
public String toString() {
return "PedidosXsaladaBusca [id_pedidos=" + id_pedidos + ", informacao_adicionais=" + informacao_adicionais
+ ", mesa=" + mesa + ", nome_sobrenome_cliente=" + nome_sobrenome_cliente + ", nome_xsalada="
+ nome_xsalada + ", total_a_pagar=" + total_a_pagar + "]";
}
}
PedidosDAO.java
public class PedidosDAO {
// Setando Caminhos
private static final String URL = "http://192.168.0.1:8080/BancoParaXsalada/services/PedidosDAO?wsdl";
private static final String nameSpace = "http://xsalada.com.br";
// referencias ao metodos no SoapUI XML file
private static final String BUSCAR = "buscarTodos";
// metodo inserir no banco pelo android usando biblioteca Ksoap2
public ArrayList<PedidosXsaladaBusca> buscarTodos() {
ArrayList<PedidosXsaladaBusca> lista = new ArrayList<PedidosXsaladaBusca>();
SoapObject buscarTodos = new SoapObject(nameSpace, BUSCAR);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(buscarTodos);
envelope.implicitTypes = true;
HttpTransportSE http = new HttpTransportSE(URL);
try {
http.call("urn:" + BUSCAR, envelope);
Vector<SoapObject> resposta = (Vector<SoapObject>) envelope.getResponse();
for (SoapObject soapObject : resposta) {
PedidosXsaladaBusca user = new PedidosXsaladaBusca();
user.setId_pedidos(Integer.parseInt(soapObject.getProperty("id_pedidos").toString()));
user.setInformacao_adicionais(soapObject.getProperty("informacao_adicionais").toString());
user.setMesa(Integer.parseInt(soapObject.getProperty("mesa").toString()));
user.setNome_sobrenome_cliente(soapObject.getProperty("nome_sobrenome_cliente").toString());
user.setNome_xsalada(soapObject.getProperty("nome_xsalada").toString());
user.setTotal_a_pagar(Double.parseDouble(soapObject.getProperty("total_a_pagar").toString()));
lista.add(user);
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return lista;
}
}
MainActivity.java
public class MainActivity extends Activity {
public ListView listaUsuario = (ListView) findViewById(R.id.listaPedidos);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
PedidosDAO dao = new PedidosDAO();
ArrayList<PedidosXsaladaBusca> lista = dao.buscarTodos();
ArrayAdapter<PedidosXsaladaBusca> adpUser = new ArrayAdapter<PedidosXsaladaBusca>(this,
android.R.layout.simple_list_item_1, lista);
listaUsuario.setAdapter(adpUser);
}
Resolved, it was not code error I realized he was giving the following error: [timestamp - DDMs] Can not bind to site 8600 is debugger
then researched and solve. below is the link I found to resolve the error:
Eclipse DDMS error "Can't bind to local 8600 for debugger"
I try to use KSOAP2 with Basic Authentication. I´m download ksoap2-android-assembly-3.0.0-jar-with-dependencies.jar, ksoap2-extras-3.0.0.jar, ksoap2-extra-ntlm-3.0.0.jar. I Tried to use the code below:
ArrayList<HeaderProperty> headerProperty = new ArrayList<HeaderProperty>();
headerProperty.add(new HeaderProperty("Authorization", "Basic " +
org.kobjects.base64.Base64.encode("user:password".getBytes())));
it's generate the error:
java.io.IOException: HTTP request failed, HTTP status: 401
ERROR:java.io.IOException:HTTP request failed, HTTP status: 401
I Tried to use the code below too:
HttpTransportBasicAuth androidHttpTpAut = new HttpTransportBasicAuth(URL, "user", "password");
androidHttpTpAut.getServiceConnection().connect();
again not work, generate the error:
Exception in thread "main" java.lang.NoClassDefFoundError: org/ksoap2/transport/HttpTransport
at java.lang.ClassLoader.defineClass1(Native Method)
Anybody do this work fine ?
After many test, I found that the code below need to change:
ArrayList headerProperty = new ArrayList();
headerProperty.add(new HeaderProperty("Authorization", "Basic " +
org.kobjects.base64.Base64.encode("user:password".getBytes())));
androidHttpTransport.call(SOAP_ACTION, envelope);
Change above androidHttpTransport.call() to below polymorphic method:
androidHttpTransport.call(SOAP_ACTION, envelope, headerProperty);
It´s necessary put the parameter headerProperty in method androidHttpTransport.call.
And, I use only ksoap2-android-assembly-3.0.0-jar-with-dependencies.jar in project.
Thanks
You can try the following code. It worked in my case, hope it will help you too.
Create a class called HttpTransportBasicAuth
import org.ksoap2.transport.*;
import org.ksoap2.transport.HttpTransportSE;
import java.io.*;
public class HttpTransportBasicAuth extends HttpTransportSE {
private String username;
private String password;
public HttpTransportBasicAuth(String url, String username, String password) {
super(url);
this.username = username;
this.password = password;
}
public ServiceConnection getServiceConnection() throws IOException {
ServiceConnectionSE midpConnection = new ServiceConnectionSE(url);
addBasicAuthentication(midpConnection);
return midpConnection;
}
protected void addBasicAuthentication(ServiceConnection midpConnection) throws IOException {
if (username != null && password != null) {
StringBuffer buf = new StringBuffer(username);
buf.append(':').append(password);
byte[] raw = buf.toString().getBytes();
buf.setLength(0);
buf.append("Basic ");
org.kobjects.base64.Base64.encode(raw, 0, raw.length, buf);
midpConnection.setRequestProperty("Authorization", buf.toString());
}
}
}
And then, change the following in your proxy class (refer the proxy class below)
protected org.ksoap2.transport.Transport createTransport()
{
return new HttpTransportBasicAuth(url,username,password);
}
Proxy class
import java.util.List;
import org.ksoap2.HeaderProperty;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.AttributeContainer;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
public class Z_WS_SCAN_REPLENISHMENT
{
interface IWcfMethod
{
ExtendedSoapSerializationEnvelope CreateSoapEnvelope() throws java.lang.Exception;
Object ProcessResult(ExtendedSoapSerializationEnvelope envelope,SoapObject result) throws java.lang.Exception;
}
String url="http://example.com/z_ws_scan_replenishment/200/z_ws_scan_replenishment/z_ws_scan_replenishment";
String username = "username";
String password = "password";
int timeOut=60000;
public List< HeaderProperty> httpHeaders;
IServiceEvents callback;
public Z_WS_SCAN_REPLENISHMENT(){}
public Z_WS_SCAN_REPLENISHMENT (IServiceEvents callback)
{
this.callback = callback;
}
public Z_WS_SCAN_REPLENISHMENT(IServiceEvents callback,String url)
{
this.callback = callback;
this.url = url;
}
public Z_WS_SCAN_REPLENISHMENT(IServiceEvents callback,String url,int timeOut)
{
this.callback = callback;
this.url = url;
this.timeOut=timeOut;
}
protected org.ksoap2.transport.Transport createTransport()
{
return new HttpTransportBasicAuth(url,username,password);
}
protected ExtendedSoapSerializationEnvelope createEnvelope()
{
return new ExtendedSoapSerializationEnvelope();
}
protected void sendRequest(String methodName,ExtendedSoapSerializationEnvelope envelope,org.ksoap2.transport.Transport transport) throws java.lang.Exception
{
transport.call(methodName, envelope,httpHeaders);
}
Object getResult(Class destObj,SoapObject source,String resultName,ExtendedSoapSerializationEnvelope __envelope) throws java.lang.Exception
{
if (source.hasProperty(resultName))
{
Object j=source.getProperty(resultName);
if(j==null)
{
return null;
}
Object instance=__envelope.get((AttributeContainer)j,destObj);
return instance;
}
else if( source.getName().equals(resultName)) {
Object instance=__envelope.get(source,destObj);
return instance;
}
return null;
}
public Bapireturn1 ZScanReplenishment(final String ILgnum,final String IPernr,final String IScannedId,final String IScannedLgpl ) throws java.lang.Exception
{
return (Bapireturn1)execute(new IWcfMethod()
{
#Override
public ExtendedSoapSerializationEnvelope CreateSoapEnvelope(){
ExtendedSoapSerializationEnvelope __envelope = createEnvelope();
SoapObject __soapReq = new SoapObject("urn:sap-com:document:sap:soap:functions:mc-style", "ZScanReplenishment");
__envelope.setOutputSoapObject(__soapReq);
PropertyInfo __info=null;
__info = new PropertyInfo();
__info.namespace="";
__info.name="ILgnum";
__info.type=PropertyInfo.STRING_CLASS;
__info.setValue(ILgnum);
__soapReq.addProperty(__info);
__info = new PropertyInfo();
__info.namespace="";
__info.name="IPernr";
__info.type=PropertyInfo.STRING_CLASS;
__info.setValue(IPernr);
__soapReq.addProperty(__info);
__info = new PropertyInfo();
__info.namespace="";
__info.name="IScannedId";
__info.type=PropertyInfo.STRING_CLASS;
__info.setValue(IScannedId);
__soapReq.addProperty(__info);
__info = new PropertyInfo();
__info.namespace="";
__info.name="IScannedLgpl";
__info.type=PropertyInfo.STRING_CLASS;
__info.setValue(IScannedLgpl);
__soapReq.addProperty(__info);
return __envelope;
}
#Override
public Object ProcessResult(ExtendedSoapSerializationEnvelope __envelope,SoapObject __result)throws java.lang.Exception {
return (Bapireturn1)getResult(Bapireturn1.class,__result,"EReturn",__envelope);
}
},"");
}
protected Object execute(IWcfMethod wcfMethod,String methodName) throws java.lang.Exception
{
org.ksoap2.transport.Transport __httpTransport=createTransport();
ExtendedSoapSerializationEnvelope __envelope=wcfMethod.CreateSoapEnvelope();
sendRequest(methodName, __envelope, __httpTransport);
Object __retObj = __envelope.bodyIn;
if (__retObj instanceof SoapFault){
SoapFault __fault = (SoapFault)__retObj;
throw convertToException(__fault,__envelope);
}else{
SoapObject __result=(SoapObject)__retObj;
return wcfMethod.ProcessResult(__envelope,__result);
}
}
java.lang.Exception convertToException(SoapFault fault,ExtendedSoapSerializationEnvelope envelope)
{
return new java.lang.Exception(fault.faultstring);
}
}
These changes did the magic for me. Hope it will work for you as well.