I am trying to build my first app for blackberry mobile's but i am new # mobile development and i am cant find the correct way to connect my app with my webiste rest API can anyone guide me where to start from?
Thanx in advance :D
HttpConnection conn = null;
InputStream is = null;
ByteArrayOutputStream bos = null;
String response = null;
String connectionURL = null;
try {
connectionURL = "THIS CONTAIN YOUR API URL"
conn = (HttpConnection) Connector.open(connectionURL);
conn.setRequestProperty("Content-Type","application/json");
System.out.println("Response code : "+conn.getResponseCode());
if(conn.getResponseCode() == HttpConnection.HTTP_OK)
{
is = conn.openInputStream();
int ch=-1;
bos = new ByteArrayOutputStream();
while((ch = is.read())!=-1)
{
bos.write(ch);
}
response = new String(bos.toByteArray());
System.out.println("Response : "+response);
}
} catch (Exception e)
{
System.out.println("Exception .."+e);
}finally
{
if(conn != null)
conn.close();
if(is != null)
is.close();
if(bos != null)
bos.close();
}
Related
Now I am developing an in app purchase of iOS using flutter. This is my verify code snipping when client purchasing success:
void _listenToPurchaseUpdated(List<PurchaseDetails> purchaseDetailsList, Context<PayState> ctx) {
purchaseDetailsList.forEach((PurchaseDetails purchaseDetails) async {
if (purchaseDetails.status == PurchaseStatus.pending) {
RestLog.logger("PurchaseStatus pending..." + ctx.state.payModel.isAvailable.toString());
_showPendingUI(ctx);
} else {
if (purchaseDetails.status == PurchaseStatus.error) {
RestLog.logger("PurchaseStatus error");
_handleError(purchaseDetails.error!, ctx);
} else if (purchaseDetails.status == PurchaseStatus.purchased || purchaseDetails.status == PurchaseStatus.restored) {
RestLog.logger("purchase successful trigger verify");
PayVerifyModel payVerifyModel =
PayVerifyModel(orderId: purchaseDetails.purchaseID, receipt: purchaseDetails.verificationData.serverVerificationData, isSandBox: true);
Pay.verifyUserPay(payVerifyModel);
}
if (purchaseDetails.pendingCompletePurchase) {
await InAppPurchase.instance.completePurchase(purchaseDetails);
}
}
});
}
the problem is I do not know which env of pay env, now I am test so I pass the isSandBox is true. How to know the isSandBox from current running context? what should I do to make it dynamic?
actually you did not need to care the env is sandbox or production, you can always using production url first, the server will return 21007 if the recipt is generate in sandbox, after recieved the 21007 code, you could try again to verify in sandbox:
private static JSONObject validateApplePay(BuySuccessRequest request, String url) {
try {
HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setAllowUserInteraction(false);
PrintStream ps = new PrintStream(connection.getOutputStream());
// Base64.Encoder encoder = Base64.getEncoder();
// String base64String = encoder.encodeToString(request.getReceipt().getBytes(StandardCharsets.UTF_8));
ps.print("{\"receipt-data\": \"" + request.getReceipt() + "\"}");
ps.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String str;
StringBuffer sb = new StringBuffer();
while ((str = br.readLine()) != null) {
sb.append(str);
}
// String encodeToString = Base64.getEncoder().encodeToString("Test".getBytes());
br.close();
String resultStr = sb.toString();
JSONObject result = JSONObject.parseObject(resultStr);
if (result != null && result.getInteger("status").intValue() == ApplePayVerifyResponseType.SANDBOX_SEND_TO_PRODUCTION.getKey().intValue()) {
return validateApplePay(request, SAND_BOX_VERIFY_URL);
}
return result;
} catch (Exception e) {
log.error("Validate pay failed", e);
}
return null;
}
this is the advice of apple.
Im trying to use http post to transfer data from flutter to SAP. I can get data without any problem, but post attempt is failing with code 403 (x-csrf-token invalid)
I had the same problem while working in C# but that was resolved using event handler, that triggers just before save (please see below extract of C# code) but i'm unable to find option in flutter. Please guide..
zZSSALE1SRVEntity.SendingRequest2 += new EventHandler<SendingRequest2EventArgs>(_container_SendingRequest_Enhance);
zZSSALE1SRVEntity.SaveChanges();
private void _container_SendingRequest_Enhance(object sender, SendingRequest2EventArgs e)
{
HttpWebResponse response;
string empty = string.Empty;
string str = string.Empty;
CookieContainer cookieContainer = new CookieContainer();
OdataSsaleDEV.ZZSSALE1_SRV_Entities zZSSALE1SRVEntity = new OdataSsaleDEV.ZZSSALE1_SRV_Entities(app_uri)
{
Credentials = credentials
};
string str1 ;
if (empty == string.Empty)
{
HttpWebRequest credentials = (HttpWebRequest)WebRequest.Create(zZSSALE1SRVEntity.BaseUri);
credentials.Method = "GET";
credentials.Headers.Add("X-CSRF-Token", "Fetch");
credentials.Credentials = zZSSALE1SRVEntity.Credentials;
cookieContainer = new CookieContainer();
credentials.CookieContainer = cookieContainer;
try
{
response = (HttpWebResponse)credentials.GetResponse();
}
catch (WebException webException)
{
MessageBox.Show(webException.Message);
return;
}
catch (Exception exception)
{
MessageBox.Show(exception.Message);
return;
}
empty = response.Headers.Get("X-CSRF-Token");
str = response.Headers.Get("Set-Cookie");
credentials.Abort();
}
if (empty != string.Empty)
{
e.RequestMessage.SetHeader("x-csrf-token", empty);
foreach (Cookie cooky in cookieContainer.GetCookies(zZSSALE1SRVEntity.BaseUri))
{
str1 = string.Concat(str1, ";", cooky.ToString());
}
e.RequestMessage.SetHeader("Cookie", str1.Substring(1));
}
Issue resolved.
Actually server requires session cookies (MYSAPSSO and SAP_SESSIONID) along with x-csrf-token.
I want to call a REST API with an Unity-Script but it occurs me the Error 400 Bad Request. It is maybe because of the http-header. May you can help me. SAP offers a Code Snippet in JAVA which I want to show you first:
DataOutputStream dataOut = null;
BufferedReader in =null;
try {
//API endpoint for API sandbox
String url = "https://sandbox.api.sap.com/mlfs/api/v2/image/scene-text-
recognition";
//Available API Endpoints
//https://mlfproduction-scene-text-
recognition.cfapps.eu10.hana.ondemand.com/api/v2/image
//https://mlfproduction-scene-text-
recognition.cfapps.us10.hana.ondemand.com/api/v2/image
URL urlObj = new URL(url);
HttpURLConnection connection = (HttpURLConnection)
urlObj.openConnection();
//setting request method
connection.setRequestMethod("POST");
//adding headers
connection.setRequestProperty("content-type","multipart/form-data;
boundary=---011000010111000001101001");
//API Key for API Sandbox
connection.setRequestProperty("APIKey","----api-Key---");
//Available Security Schemes for productive API Endpoints
//OAuth 2.0
connection.setDoInput(true);
//sending POST request
connection.setDoOutput(true);
dataOut = new DataOutputStream(connection.getOutputStream());
dataOut.writeBytes("-----011000010111000001101001\r\nContent-
Disposition: form-data; name=\"files\"; filename=\"<file_name>\"\r\nContent-Type: <file_type>\r\n\r\n<file_contents>\r\n-----011000010111000001101001--");
dataOut.flush();
int responseCode = connection.getResponseCode();
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
//printing response
System.out.println(response.toString());
} catch (Exception e) {
//do something with exception
e.printStackTrace();
} finally {
try {
if(dataOut != null) {
dataOut.close();
}
if(in != null) {
in.close();
}
} catch (IOException e) {
//do something with exception
e.printStackTrace();
}
}
My UnityCode looks something like this:
public void ExecutePost()
{
Debug.Log("execute started");
byte[] img =
File.ReadAllBytes(#"C:\Users\InnovationLab\Documents\ECENTA\ECENTA
FSE\Bild1.jpg");
string url = "https://sandbox.api.sap.com/mlfs/api/v2/image/scene-
text-recognition";
coroutine = Post(url, img);
StartCoroutine(coroutine);
}
public IEnumerator Post(string url,byte[] image)
{
WWWForm form = new WWWForm();
form.AddBinaryData("imageField", image, "HoloImg");
var headers = new Dictionary<string, string> {
{"content-type", "multipart/form-data; boundary=---011000010111000001101001" },
{"APIKey", "---here I implemented the key---" }
};
WWW www = new WWW(url, image, headers);
yield return www;
if (www.error != null && www.error != "")
{ // on error, show information and return
Debug.Log("Network Error occured: " + www.error);
yield break;
}
while (!www.isDone)
{
Debug.Log(www.text);
}
}
}
So my question is, how to change the unity code so that it works?
I fixed it by using MultipartFormSections. The problem was that the api expected form-data not a binary Array.
public IEnumerator Upload(string url, byte[] img)
{
List<IMultipartFormSection> formData = new List<IMultipartFormSection>();
MultipartFormFileSection myFormFile = new MultipartFormFileSection("files", img,
"Bild1.jpg", "multipart/form-data");
formData.Add(myFormFile);
Debug.Log(formData.ToString());
UnityWebRequest www = UnityWebRequest.Post(url, formData);
www.SetRequestHeader("APIKey", "<api-key>");
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
throw new Exception(www.downloadHandler.text ?? www.error);
}
else
{
Debug.Log("Done!!!!!");
}
Debug.Log(www.downloadHandler.text);
var ResultObject = JsonUtility.FromJson<TextPrediction>(www.downloadHandler.text);
foreach (var result in ResultObject.texts)
{
}
}
I have no problems running my applet in Eclipse, but if I sign and run it in browser this happend
10-abr-2013 19:54:37 org.apache.http.impl.client.DefaultHttpClient tryConnect
INFO: I/O exception (java.net.SocketException) caught when connecting to the target host: Unknown proxy type : HTTP
10-abr-2013 19:54:37 org.apache.http.impl.client.DefaultHttpClient tryConnect
INFO: Retrying connect
…
java.net.SocketException: Unknown proxy type : HTTP
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
Here im trying to upload some files using org.apache.http.client.HttpClient
public static String executeMultiPartRequest(String urlString, File file,
String fileName, String fileDescription) {
System.out.println("SET URI " + urlString);
HttpPost postRequest = new HttpPost(urlString);
try {
MultipartEntity multiPartEntity = new MultipartEntity();
// The usual form parameters can be added this way
multiPartEntity.addPart("fileDescription", new StringBody(
fileDescription != null ? fileDescription : ""));
multiPartEntity.addPart("fileName", new StringBody(
fileName != null ? fileName : file.getName()));
/*
* Need to construct a FileBody with the file that needs to be
* attached and specify the mime type of the file. Add the fileBody
* to the request as an another part. This part will be considered
* as file part and the rest of them as usual form-data parts
*/
FileBody fileBody = new FileBody(file, "application/octect-stream");
multiPartEntity.addPart("attachment", fileBody);
// multiPartEntity.addPart("path", Charset.forName("UTF-8"));
postRequest.setEntity(multiPartEntity);
} catch (UnsupportedEncodingException ex) {
ex.printStackTrace();
}
return executeRequest(postRequest);
}
private static String executeRequest(HttpRequestBase requestBase) {
String responseString = "";
InputStream responseStream = null;
HttpClient client = new DefaultHttpClient();
try {
System.out.println("LISTO PARA ENVIAR A" + requestBase.getURI());
HttpResponse response = client.execute(requestBase);
if (response != null) {
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
responseStream = responseEntity.getContent();
if (responseStream != null) {
BufferedReader br = new BufferedReader(
new InputStreamReader(responseStream));
String responseLine = br.readLine();
String tempResponseString = "";
while (responseLine != null) {
tempResponseString = tempResponseString
+ responseLine
+ System.getProperty("line.separator");
responseLine = br.readLine();
}
br.close();
if (tempResponseString.length() > 0) {
responseString = tempResponseString;
}
}
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (responseStream != null) {
try {
responseStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
client.getConnectionManager().shutdown();
return responseString;
}
What its wrong?
Applet is signed and compiled with java 1.6, httpclient-4.1.3.jar
For those with this problem, the solution was here http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d5e571 getting the JRE Proxy.
DefaultHttpClient client = new DefaultHttpClient () ;
ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
client.getConnectionManager().getSchemeRegistry(),
ProxySelector.getDefault());
client.setRoutePlanner(routePlanner);
HttpResponse response = client.execute(requestBase) ;
Then i signed all libraries httpcore-4.2.3.jar, httpmime-4.2.3.jar and httpclient-4.2.3.jar.
I'm trying to connect to the internet via my J2ME application on my Netbeans emulator with the following function which connects to a webpage and prints out its HTML using System.out.println().
function getHTML(String url)
{
HttpConnection httpConn = null;
InputStream is = null;
OutputStream os = null;
try
{
httpConn = (HttpConnection)Connector.open(url);
int respCode = httpConn.getResponseCode();
if (respCode == httpConn.HTTP_OK)
{
StringBuffer sb = new StringBuffer();
os = httpConn.openOutputStream();
is = httpConn.openDataInputStream();
int chr;
while ((chr = is.read()) != -1)
sb.append((char) chr);
System.out.println(sb.toString());
os.close();
is.close();
}
else
{
System.out.println("Error " + respCode);
}
httpConn.close();
}
catch(IOException ioex)
{
ioex.printStackTrace();
}
}
But I've been getting the following error;
javax.microedition.io.ConnectionNotFoundException: error 10051 in socket::open
at com.sun.midp.io.j2me.socket.Protocol.open0(), bci=0
at com.sun.midp.io.j2me.socket.Protocol.connect(), bci=209
at com.sun.midp.io.j2me.socket.Protocol.open(), bci=216
at com.sun.midp.io.j2me.socket.Protocol.openPrim(), bci=4
at com.sun.midp.io.j2me.http.Protocol.createConnection(), bci=41
at com.sun.midp.io.j2me.http.Protocol.connect(), bci=41
at com.sun.midp.io.j2me.http.Protocol.streamConnect(), bci=164
at com.sun.midp.io.j2me.http.Protocol.startRequest(), bci=7
at com.sun.midp.io.j2me.http.Protocol.sendRequest(), bci=33
at com.sun.midp.io.j2me.http.Protocol.sendRequest(), bci=3
at com.sun.midp.io.j2me.http.Protocol.getResponseCode(), bci=5
I know my code isn't the problem because this used to work on my old laptop, but it hasn't worked since I installed Netbeans on my new laptop. Is it because of my internet connection, or my firewall settings, or my settings in Netbeans, or did I just not install Netbeans properly?
If you want to send some data and receive means then try the coding
try
{
httpConn = (HttpConnection)Connector.open(url);
os = httpConn.openOutputStream();
//Writing data to os
os.write(b); //Here b is a byte array
os.flush();
int respCode = httpConn.getResponseCode();
if (respCode == httpConn.HTTP_OK)
{
StringBuffer sb = new StringBuffer();
is = httpConn.openDataInputStream();
int chr;
while ((chr = is.read()) != -1)
sb.append((char) chr);
System.out.println(sb.toString());
}
else
{
System.out.println("Error " + respCode);
}
}
catch(IOException ioex)
{
ioex.printStackTrace();
}
if(os!=null) os.close();
if(is!=null) is.close();
if(httpConn!=null) httpConn.close();
os=null;is=null;httpConn=null;
}