Equivalent of ClientCredentials in WCF connection from a C# WinForm? - java

What's the equivalent of ClientCredentials in WCF connection from a C# WinForm application to an HTTP request in Android Java or Swift?
ServicePointManager.ServerCertificateValidationCallback += delegate { return true; };
SvcClient objSvcClient = new SvcClient();
objSvcClient.ClientCredentials.UserName.UserName = txtUserName.Text;
objSvcClient.ClientCredentials.UserName.Password = txtPassword.Text;
int intout = objSvcClient.GetData(999);
objSvcClient.Close();
MessageBox.Show(intout.ToString());

Just add the authorization header to the http request,for more information about it, you can refer to this link:
how to pass client credentials in postman?

Related

Add Custom HTTP Header to Request sent by BlazeDS and AMF

in our application we have a flex Client, this client uses BlazeDS and AMF to excute operation,
Is there a way to add a custom Http header to the request sent from the AMF so i can read in our Filter in Java server Side
Thanks.
You can use a custom header with anything you like in it, like this:
headers = [
new URLRequestHeader("contentType", "application/x-www-form-urlencoded"),
new URLRequestHeader("Accept-Language", "en_US"),
new URLRequestHeader("X-Authorization", "Bearer " + API_KEY)
];
Then use it like:
var urlReq:URLRequest = new URLRequest(API_URL);
urlReq.method = URLRequestMethod.GET;
urlReq.requestHeaders = headers;
var _jsonLoader:URLLoader = new URLLoader();
_jsonLoader.load(urlReq);

Getting ​Transfer-Encoding=chunked instead of content length in soap ws call

I am trying to call two soap ws and from java. When I'm calling these ws from two different java thread it's successfully called but when tried to call in same thread, first call get successful and second call get stuck. I can see both the request in my logs.
I checked tcp dump at server and can see for first request, all the header parameter is set correctly but in second call instead of content-length getting transfer-encoding = chunked.
first ws call header - 2/15/2018 9:59:40 AM [8]
Content-Length=639 Content-Type=text/xml; charset=UTF-8 Accept=/ Host=test102.com User-Agent=Apache CXF
2.7.11 SOAPAction="Trackem.Web.Services/ReserveServiceTime" Proxy-Connection=Keep-Alive
Second ws call header - 2/15/2018 10:01:11 AM [9]
Transfer-Encoding=chunked Content-Type=text/xml; charset​​=UTF-8 Accept=/ Host=test102.com
User-Agent=Apache CXF 2.7.11
SOAPAction="Trackem.Web.Services/CreateOrUpdateTask"
Proxy-Connection=Keep-Alive5:05 PM
Please help me do understand why second call is not working properly?
Here is my java ws method -
public P getPort(final Class<P> serviceEndpointInterface, final String ascNode) throws MalformedURLException{
final Bus currThreadBus = BusFactory.getThreadDefaultBus();
ClassLoader originalThreadClassLoader = Thread.currentThread().getContextClassLoader();
ClassLoader busFactoryClassLoader = BusFactory.class.getClassLoader();
try {
Thread.currentThread().setContextClassLoader(busFactoryClassLoader);
BusFactory.setThreadDefaultBus(BusFactory.newInstance().createBus());
QName qname = new QName(nameSpace, strQName);
Service service = Service.create(qname);
P port = null;
if (CommonUtil.isEmpty(portName)) {
port = service.getPort(serviceEndpointInterface);
} else {
QName portQname = new QName(nameSpace, portName);
port = service.getPort(portQname, serviceEndpointInterface);
}
BindingProvider bp = (BindingProvider) port;
// Timeout in millis
bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, serviceURL);
bp.getRequestContext().put(Message.CONNECTION_TIMEOUT, Integer.parseInt(connectTimeout));
bp.getRequestContext().put(Message.RECEIVE_TIMEOUT, Integer.parseInt(requestTimeout));
final Client client = ClientProxy.getClient(port);
client.getOutInterceptors().add(new LoggingOutInterceptor());
client.getInInterceptors().add(new LoggingInInterceptor());
//Add proxy server details if configured in ASC
if(!CommonMethods.isEmpty(proxyHost) && !CommonMethods.isEmpty(proxyPort))
{
HTTPConduit http = (HTTPConduit) ClientProxy.getClient(port).getConduit();
http.getClient().setProxyServer(proxyHost);
http.getClient().setProxyServerPort(Integer.parseInt(proxyPort));
if(!CommonMethods.isEmpty(proxyUsername) && !CommonMethods.isEmpty(proxyPassword))
{
http.getProxyAuthorization().setUserName(proxyUsername);
http.getProxyAuthorization().setPassword(proxyPassword);
}
}
return port;
}finally {
BusFactory.setThreadDefaultBus(currThreadBus);
Thread.currentThread().setContextClassLoader(originalThreadClassLoader);
}}
I solved this issue by disabling chunk transfer in HTTP client.
http.getClient().setAllowChunking(false);
I guess, the problem was in my proxy serve see this link

Android HttpURLConnection receives HTTP 301 response code

I'm trying to do a HTTP GET using the HttpURLConnection object in Android.
UPDATE
I tried connection to a different server. This is also hosted within Cloud 9 (c9.io) and also returns a json response. This time I'm not getting a 301 redirect, but I am getting the actual response the server is supposed to send.
Since this means the problem is localised within the server, I've reorganized the following sections in order to focus reading onto the server-related information. Android related information has been moved to the end of the question.
Where I am connecting:
Development server on Cloud9
Using the Laravel Framework 5.2 (we cannot upgrade to 5.3 at this time, due to unsupported project dependencies)
The server should return a JSON answer
If I connect to the same URL through the browser I get the correct response (JSON string. Required HTTP Headers and a '200' HTTP Response Code)
Where I am connecting FROM
Android phone (Oneplus 3, on Android 6.0)
Compile SDK version: 23
Using Build Tools: "23.0.3"
Using Min SDK verion: 19
Using Target SDK version: 22
I'm connectiong using a HttpURLConnection object, using HTTP Method 'GET'
HTTP Response on Android
When I run my code I get the folling result from the server:
The HTTP response code is 301 but the message is null.
The new URL is exactly the same, but using HTTPS. It seems server is somehow forcing SSL/TSL encryption. Which does not happen when accessing HTTP from the browser.
HTTP Header (on Android):
date => Tue, 04 Oct 2016 05:56:26 GMT
location => https://domain.com/route/ (I modified this bit)
content-length => 382
content-type => text/html; charset=iso-8859-1
X-BACKEND => apps-proxy
X-Android-Selected-Protocol => http/1.1
X-Android-Sent-Millis => 1475560583894
X-Android-Received-Millis => 1475560585637
X-Android-Response-Source => NETWORK 301
null => HTTP/1.1 301
Other data
Since it seems the server wants Android to use HTTPS, I tried modifying the code to use HTTPS (HttpsURLConnection). This may or may not solve this problem, but I am unable to check it since I get an annoying SSL handshake failed error. Plus I have no need for encryption on this application, and therefore I'm reluctant to solve the problems coming with it.
This is all running within an AsyncTask object (since Android get moody when you try to use a network connection on the main thread).
Setting up a new server (outside of Cloud 9 and without any SSL/TSL) could be an option, but I'm reluctant to do this since it would be quite time consuming.
I tried connecting to another Cloud 9 server (which also returns a json response), using the exact same code, and everything works correctly. This suggests that the problem arises from the HTPP 301 error.
I will try to share with you any other information you may require to answer my question!
Native Android stuff (moved on UPDATE, see above)
The response content seems to be an incomplete JSON:
{ 'status':'ERROR'
Note I did NOT forget the closing } character, that's what the response actually containts. This is injected somewhere unknown (to me) during the workflow. When I capture the HTTP response (using Charles on my PC, which is set as a Proxy for my phone's Wi-Fi connection) it's content is (as expected) a simple HTML telling you to redirect (HTPP code 301) to a new route.
The invalid JSON code (above) isn't there, but a valid HTML is.
This would suggest that the invalid JSON appears somewhere internally to my code (not on the server, or transport). But there is no code on my app that generates a JSON string, let alone inject it into the response I'm processing.
Code for the HttpURLConnection
this.setURL(ruta); //gets correct url
HttpURLConnection cxn = (HttpURLConnection) this.getURL().openConnection(); //init
cxn.setRequestMethod("GET"); //use HTTP GET verb
cxn.setUseCaches(false); //no cache
cxn.setRequestProperty("Cache-Control", "no-cache"); //even less cache
cxn.setDoOutput(false); //only true in POST/PUT requests
cxn.setRequestProperty("Connection","keep-alive");
cxn.setRequestProperty("DNT", "1"); //TEMP
cxn.setInstanceFollowRedirects(true); //should follow redirects
cxn.setRequestProperty( "charset", "utf-8");
Code for the reading the result
int status_code = cxn.getResponseCode();
InputStream responseStream = new BufferedInputStream(cxn.getInputStream());
BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));
String line = "";
StringBuilder stringBuilder = new StringBuilder();
while ((line = responseStreamReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
responseStreamReader.close();
String response = stringBuilder.toString();
cxn.disconnect();
Remove the code you've used to create the HttpURLConnection and try with this one:
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL("http://www.domain.com/index.aspx?parameter1=X&parameter2=X"); //Use your url and add the GET parameters
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setInstanceFollowRedirects(false); /* added line */
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
System.out.print(current);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
This should be all you need to set for your GET request.
EDIT:
I've tested the webservice using Volley, here's the code I've used in order to retrieve the webservice response:
public class MainActivity extends AppCompatActivity {
public String response;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.rTextView);
RequestQueue queue = Volley.newRequestQueue(this);
String url = "yourWebserviceUrl";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener < String > () {
#Override
public void onResponse(String response) {
textView.setText("Response is: " + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
textView.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
}
And this is the response I got:
{"status":"ok","found":false,"extra":"App\\Scanners"}
Changing the protocol to https worked for me.
I faced the same problem, and I fixed it after reading this source.
All we need to do is handling 3** errors like shown below
if(responseCode > 300 && responseCode < 400) {
String redirectHeader = conn.getHeaderField("Location");
if(TextUtils.isEmpty(redirectHeader)) {
return new JsonResponse(responseCode, "Failed to redirect");
}
JsonRequest newRequest = request;
newRequest.url = redirectHeader;
return getJsonFromUrl(newRequest);
}
Each 3** response should have a header with name Location which contains a redirect link which we should use.
Change the line :
HttpURLConnection cxn = (HttpURLConnection) this.getURL().openConnection();
with :
HttpsURLConnection cxn = (HttpsURLConnection) this.getURL().openConnection();
So you will able to handle https

PHP RESTful API accessing Jersey Client POST data

I am using a PHP RESTful API which is consumed by a Java desktop application using jersey 2.21.
Usually, when I send a POST request from AngularJS, I can access the data via:
$data = json_decode(file_get_contents("php://input"));
However, when I use jersey, the data is put in the $_POST array. Here is my Jersey code:
final HashMap<String, String> params = // some hashmap with a few entries
ClientConfig config = new ClientConfig();
Client client = ClientBuilder.newClient(config);
MultivaluedMap formData = new MultivaluedHashMap(params);
WebTarget target = client.target(url);
// Get JSON
String jsonResponse = target.request(MediaType.APPLICATION_JSON_TYPE).post(Entity.entity(formData, MediaType.APPLICATION_FORM_URLENCODED_TYPE), String.class);
return jsonResponse;
How do I post the data from Jersey so that I can access it via the above PHP call?
I know I can just use the $_POST array, but I need this API to be consumed from a mobile app, Java desktop & an AngularJS app.
Thanks in advance
Thanks to #jonstirling, I got it.
I had to set the content type as JSON. here is the updated code:
ClientConfig config = new ClientConfig();
Client client = ClientBuilder.newClient(config);
WebTarget target = client.target(url);
String data = new Gson().toJson(params);
// POST JSON
Entity json = Entity.entity(data, MediaType.APPLICATION_JSON_TYPE);
Invocation.Builder builder = target.request(MediaType.APPLICATION_JSON_TYPE);
String jsonResponse = builder.post(json, String.class);
return jsonResponse;

Send XMLRPC Request using Java

I am trying to send an XMLRPC Request via Java and is unsuccessful. Here's the structure of XMLRPC Request that I need to send with method name create.account:
<createaccount>
<functioncode>bank_account</functioncode> <cardnumber>55553263654898</cardnumber>
<transaction_id>12345678</transaction_id>
<transactiondatetime>2012-01-08 14:12:22</transactiondatetime>
</createaccount>
As per client, I should be expecting the following XMLRPC Response:
<createaccount>
<code>200</code>
<message>SUCCESS</message>
<functioncode>bank_account</functioncode>
<cardnumber>55553263654898</cardnumber>
<transaction_id>12345678</transaction_id>
<transactiondatetime>2012-01-08 14:12:22</transactiondatetime>
</createaccount>
I have made the following snippet in java but I'm getting an error: 'Failed to create input stream: Server returned HTTP response code: 500 for URL'
Here's the snippet:
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
config.setServerURL(new URL(server_url));
XmlRpcClient client = new XmlRpcClient();
config.setBasicUserName(pUser);
config.setBasicPassword(pPassword);
client.setConfig(config);
Map m = new HashMap();
m.put("functioncode", "bank_account");
m.put("cardnumber", "55553263654898");
m.put("transaction_id", "12345678");
m.put("transactiondatetime", "2012-01-08 14:12:22");
Object[] params = new Object[]{m};
String result = (String)client.execute("bank.account", params);
System.out.println("Results:" + result);
How I can do this?
I would recommend using XML-RPC library, for example Redston XML-RPC. More info and tutorial can be found here.

Categories

Resources