Sinch java error - sinch

i am using sinch from java, i recently reput credit to the account, and now when i try to send message i get succes message, but the sms isn't send. Following the link https://messagingapi.sinch.com/v1/sms/162393899 i get this
{"errorCode":40107,"message":"Invalid authorization key:
vivi******#gmail.com","reference":"BA:vivi******#gmail.com_GtIfKPDMJEKL4VJWR0kkJQ"}
the code
try {
String phoneNumber = "+40732******";
String appKey = "*****";
String appSecret = "****";
String message = "Test";
URL url = new URL("https://messagingapi.sinch.com/v1/sms/" + phoneNumber);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
String userCredentials = "application\\" + appKey + ":" + appSecret;
byte[] encoded = Base64.encodeBase64(userCredentials.getBytes());
String basicAuth = "Basic " + new String(encoded);
connection.setRequestProperty("Authorization", basicAuth);
String postData = "{\"Message\":\"" + message + "\"}";
OutputStream os = connection.getOutputStream();
os.write(postData.getBytes());
StringBuilder response = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ( (line = br.readLine()) != null)
response.append(line);
br.close();
os.close();
System.out.println(response.toString());
} catch (IOException e) {
e.printStackTrace();
}

Related

the request was rejected because no multipart boundary was found when creating new document in Docushare Flex

I am trying to create new document in Docushare Flex using new docushare rest api and my request body suppose to be XML and I am generating it with requested data, when I send the request I get this error "org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found"
HttpPost request = new HttpPost(postUrl);
String filePath = "C:/Test/CreateDocument.xml";
String createObj = helper.createDocumentXml(filePath, parentId, documentTitle, fileName, ownerId);
String createDocumentXml= null;
{
try {
createDocumentXml = FileUtils.readFileToString(new File(filePath));
} catch (IOException e) {
e.printStackTrace();
}
}
StringEntity bodyEntity = new StringEntity(createDocumentXml, ContentType.MULTIPART_FORM_DATA);
request.setEntity(bodyEntity);
CloseableHttpResponse response = client.execute(request);
System.out.println("Status is " + response.getStatusLine());
HttpEntity entity = response.getEntity();
I have used this block of code to upload a document in DocuShare Flex
HttpPost request = new HttpPost(postUrl);
String filePath = "C:/Test/CreateDocument.xml";
String createObj = helper.createDocumentXml();
String createDocumentXml= null;
{
try {
createDocumentXml = FileUtils.readFileToString(new File(filePath));
} catch (IOException e) {
e.printStackTrace();
}
}
FileBody body = new FileBody(file.toFile());
StringBody xmlContent = new StringBody(createDocumentXml, ContentType.APPLICATION_XML);
String boundry = UUID.nameUUIDFromBytes(file.toString().getBytes()).toString();
HttpEntity entity = MultipartEntityBuilder.create()
.setBoundary(boundry)
.setCharset(Charset.forName("UTF-8"))
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)`enter code here`
.addPart("content", body)
.addPart("request", xmlContent)
.build();
request.setEntity(entity);
CloseableHttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();

Auth Exception in Pinterest API

I am getting { "status": "failure", "code": 3, "host": "coreapp-devplatform-devapi-173", "generated_at": "Tue, 29 Sep 2015 05:42:42 +0000", "message": "Authorization failed.", "data": null } exception while invoking https://api.pinterest.com/v1/oauth/token?code=&client_id=&grant_type=authorization_code. Can anyone help me to resolve this?
Code:
if (request.getParameter("code") != null) {
code = request.getParameter("code");
}
String authorizeUrl = "https://api.pinterest.com/v1/oauth/token";
String postStr = "code=" + code + "&client_id=" + clientId + "&grant_type=authorization_code";
String responseStr = postTokenRequest(authorizeUrl, postStr);
//Method
public String postTokenRequest(String serverURL, String content) {
String inputLine = "";
HttpsURLConnection connection = null;
URL url = new URL(serverURL);
String method = "POST";
InputStream connectionIn = null;
BufferedReader buffer = null;
try {
connection = (HttpsURLConnection) url.openConnection();
connection.setRequestProperty("Content-Length", String.valueOf(content.getBytes().length));
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setDoOutput(true);
connection.getOutputStream().write(content.getBytes());
int returnCode = connection.getResponseCode();
if (returnCode == 200) {
connectionIn = connection.getInputStream();
} else {
connectionIn = connection.getErrorStream();
}
buffer = new BufferedReader(new InputStreamReader(connectionIn));
StringBuilder sb = new StringBuilder();
while ((inputLine = buffer.readLine()) != null) {
sb.append(inputLine);
}
buffer.close();
return sb.toString();
}catch(Exception e){}
}

HttpPost, HttpClient The target server failed to respond

I cannot connect to my server using HttpClient when Posting, it works fine with get, and works fine with post to other servers (such as google), any ideas?
I am NOT using android.
The server responds fine when accessing it by browser.
As it is probably a server config issue, i do not have full access to the server, it is a hosted webserver, however i have access to the cpanel
private static String GetURL(String inUrl, String post) {
String inputLine = "";
try {
if (!inUrl.contains("http")) {
throw new Exception("Invalid URL");
} else {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(inUrl);
httpPost.addHeader("Accept-Charset", "UTF-8");
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
//create post
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("req", post));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(httpPost);
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
inputLine = in.readLine();
in.close();
}
}catch (Exception ex) {
inputLine = "" + Comms.ERROR_COULD_NOT_REACH_SERVER;
Log.writeLog("Could Not Reach Server: \"" + inUrl + "\"");
ex.printStackTrace();
}
return inputLine;
}
org.apache.http.NoHttpResponseException: The target server failed to respond
at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:95)
at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:62)
at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:254)
at org.apache.http.impl.AbstractHttpClientConnection.receiveResponseHeader(AbstractHttpClientConnection.java:289)
at org.apache.http.impl.conn.DefaultClientConnection.receiveResponseHeader(DefaultClientConnection.java:252)
at org.apache.http.impl.conn.ManagedClientConnectionImpl.receiveResponseHeader(ManagedClientConnectionImpl.java:191)
at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:300)
at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:127)
at org.apache.http.impl.client.DefaultRequestDirector.tryExecute(DefaultRequestDirector.java:715)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:520)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:805)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:784)
at Comms.GetURL(Comms.java:87)
at Comms.sendCommand(Comms.java:64)
at Comms.main(Comms.java:43)

How to get an instance of DomainRuntimeService in weblogic?

This is my code:
domainService = new ObjectName("com.bea:Name=DomainRuntimeService,Type=weblogic.management.mbeanservers.domainruntime.DomainRuntimeServiceMBean");
InitialContext ctx = new InitialContext();
mBeanServer = (MBeanServer) ctx.lookup("java:comp/env/jmx/runtime");
ObjectName[] servers = (ObjectName[]) mBeanServer.getAttribute(domainService, "ServerRuntimes");
But I am getting this error. What I am doing wrong here?
javax.management.InstanceNotFoundException: com.bea:Name=DomainRuntimeService,Type=weblogic.management.mbeanservers.domainruntime.DomainRuntimeServiceMBean^M
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.getMBean(DefaultMBeanServerInterceptor.java:1094)^M
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.getAttribute(DefaultMBeanServerInterceptor.java:662)^M
at com.sun.jmx.mbeanserver.JmxMBeanServer.getAttribute(JmxMBeanServer.java:638)^M
at weblogic.management.jmx.mbeanserver.WLSMBeanServerInterceptorBase$12.run(WLSMBeanServerInterceptorBase.java:326)^M
at java.security.AccessController.doPrivileged(Native Method)^M
at weblogic.management.jmx.mbeanserver.WLSMBeanServerInterceptorBase.getAttribute(WLSMBeanServerInterceptorBase.java:324)^M
at weblogic.management.mbeanservers.internal.JMXContextInterceptor.getAttribute(JMXContextInterceptor.java:157)^M
at weblogic.management.jmx.mbeanserver.WLSMBeanServerInterceptorBase$12.run(WLSMBeanServerInterceptorBase.java:326)^M
at java.security.AccessController.doPrivileged(Native Method)^M
at weblogic.management.jmx.mbeanserver.WLSMBeanServerInterceptorBase.getAttribute(WLSMBeanServerInterceptorBase.java:324)^M
at weblogic.management.mbeanservers.internal.SecurityInterceptor.getAttribute(SecurityInterceptor.java:299)^M
at weblogic.management.jmx.mbeanserver.WLSMBeanServer.getAttribute(WLSMBeanServer.java:279)^M
at com.motive.smp.femto.deploy.wl.utils.WLUtilities.getListMServers(WLUtilities.java:105)^M
at com.motive.smp.femto.deploy.utils.DeploymentUtilsServlet.doGet(DeploymentUtilsServlet.java:58)^M
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)^M
at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)^M
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227)^
Try this:
Context context = new InitialContext();
MBeanServer domain = (MBeanServer) context.lookup("java:comp/env/jmx/domainRuntime");
DomainRuntimeServiceMBean domainRuntimeService = (DomainRuntimeServiceMBean) MBeanServerInvocationHandler.newProxyInstance(domain,
new ObjectName(DomainRuntimeServiceMBean.OBJECT_NAME));
sonnykwe's answer is ok if you are connected to the AdminServer. In my case, I was connected to one of the many managed servers in the domain.
This is what I did:
public static Map<String, String> getAdminServerInfo() {
MBeanServer mBeanServer = null;
InitialContext ctx = null;
String administrationURL = null;
String listenAddress = null;
String domainName = null;
String httpProtocol = null;
Map<String, String> serverInfo = new HashMap<String, String>();
int adminPort = 0;
try {
ctx = new InitialContext();
mBeanServer = (MBeanServer) ctx.lookup("java:comp/env/jmx/runtime");
// Get Admin Server and Port
String managedServerName = (String) mBeanServer.getAttribute(
runtimeService, "ServerName");
ObjectName msServerRuntime = new ObjectName("com.bea:Name="
+ managedServerName + ",Type=ServerRuntime");
administrationURL = (String) mBeanServer.getAttribute(
msServerRuntime, "AdminServerHost");
listenAddress = (String) mBeanServer.getAttribute(msServerRuntime,
"ListenAddress");
adminPort = (Integer) mBeanServer.getAttribute(msServerRuntime,
"AdminServerListenPort");
Boolean isSecure = (Boolean) mBeanServer.getAttribute(
msServerRuntime, "AdminServerListenPortSecure");
httpProtocol = (isSecure) ? "https" : "http";
ObjectName domainMBean = (ObjectName) mBeanServer.getAttribute(
runtimeService, "DomainConfiguration");
domainName = (String) mBeanServer.getAttribute(domainMBean, "Name");
logger.debug("AdminURL= " + administrationURL + " ,Port= "
+ adminPort + " Domain= " + domainName + " ManagedServer= "
+ managedServerName + " ListenAddress= " + listenAddress
+ " AdminServerListenPortSecure?= " + isSecure);
serverInfo.put("administrationURL", administrationURL);
serverInfo.put("managedServerName", managedServerName);
serverInfo.put("adminPort", Integer.toString(adminPort));
serverInfo.put("domainName", domainName);
serverInfo.put("listenAddress", listenAddress.substring(0, listenAddress.indexOf("/")));
serverInfo.put("httpProtocol", httpProtocol);
} catch (Exception ex) {
logger.error(
"Caught Exception while fetching Admin Server information : ",
ex);
throw new RuntimeException(
"Caught Exception while fetching Admin Server information : ",
ex);
} finally {
if (ctx != null) {
try {
ctx.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
return serverInfo;
}

Upload Image using blackberry

I want to upload an image in blackberry simulator using MultipartPostData, the following is my code but it does not seem to work. I have also signed my .cod file. Can anyone help me please?
public void postData(String Url, bytes[] data)
{
if (DeviceInfo.isSimulator()){
Url=Url+";deviceSide=true";
}
HttpConnection httpConn=null;
OutputStream os=null;
InputStream is=null;
String url=Url;
try {
PostData form = new MultipartPostData(MultipartPostData.DEFAULT_CHARSET, false) ;
byte [] postData = data;
form.setData(postData);
httpConn = (HttpConnection) Connector.open(url);
httpConn.setRequestMethod(HttpConnection.POST);
httpConn.setRequestProperty("User-Agent", "BlackBerry");
httpConn.setRequestProperty("Content-Type", "multipart/form-data");
httpConn.setRequestProperty("MIME-Type", "Image/Jpeg");
httpConn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH, String.valueOf(postData.length));
httpConn.setRequestProperty("Content-Language", "en-US");
os =httpConn.openOutputStream();
os.write(form.getBytes());
//read response
StringBuffer sb = new StringBuffer();
is = httpConn.openDataInputStream();
int chr;
while ((chr = is.read()) != -1)
sb.append((char) chr);
System.out.println("Result................................ " + sb.toString());
String result=sb.toString();
}
catch(Exception e)
{
System.out.println(e.toString());
}
finally {
try{
if(is!= null)
is.close();
if(os != null)
os.close();
if(httpConn != null)
httpConn.close();
} catch(Exception e1){
System.out.println(e1.toString());
}
}
}
//you must have a bundary format post data, the .cod file must be work on the simulator
httpConn = (HttpConnection)connDesc.getConnection();
httpConn.setRequestMethod(HttpConnection.POST);
httpConn.setRequestProperty("user-agent", "BlackBerry");
httpConn.setRequestProperty("content-type", "multipart/form-data; boundary=----------V2ymHFg03ehbqgZCaKO6jy");
os = httpConn.openOutputStream();
//os.write(form.getBytes());
byte[] fileBytes = {1,2,3,4}; //retrieve file bytes with your own code
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bos.write(("\r\n--" + "----------V2ymHFg03ehbqgZCaKO6jy" + "\r\n").getBytes());
bos.write(("Content-Disposition: form-data; name=\"mifoto\"; filename=\"leo.gif\"\r\n").getBytes());
bos.write(("Content-Type: image/gif\r\n\r\n").getBytes());
bos.write(fileBytes);
bos.write(("\r\n--" + "----------V2ymHFg03ehbqgZCaKO6jy" + "--\r\n").getBytes());
os.write(bos.toByteArray());
As soon as you call MultipartPostData.setData(), it overwrites any Content-Disposition data you have set with MultipartPostData.append().
leonel's answer works or you can use Vlad Patryshev's ClientHttpRequest class.

Resources