I am developing a Java application to be the server in a Google Cloud Messaging Android app.
I have been following a tutorial and I managed to do rest of the tutorial with out a trouble.
My Java application has three classes which are Content.java, POST2GCM.java, App.java. These classes do what the name describes.
Content.java class is below.
package com.hmkcode.vo;
import java.io.Serializable;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class Content implements Serializable {
private List<String> registration_ids;
private Map<String,String> data;
public void addRegId(String regId){
if(registration_ids == null)
registration_ids = new LinkedList<String>();
registration_ids.add(regId);
}
public void createData(String title, String message){
if(data == null)
data = new HashMap<String,String>();
data.put("title", title);
data.put("message", message);
}
}
App.java class is below
package com.hmkcode.vo;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmkcode.vo.Content;
public class App
{
public static void main( String[] args )
{
System.out.println( "Sending POST to GCM" );
String apiKey = "AIzaSyB8azikXJKi_NjpWcVNJVO0d........";
Content content = createContent();
POST2GCM.post(apiKey, content);
}
public static Content createContent(){
Content c = new Content();
c.addRegId("APA91bFqnQzp0z5IpXWdth1lagGQZw1PTbdBAD13c-UQ0T76BBYVsFrY96MA4SFduBW9RzDguLaad-7l4QWluQcP6zSoX1HSUaAzQYSmI93....");
c.createData("Test Title", "Test Message");
return c;
}
}
POST2GCM.java class is below
package com.hmkcode.vo;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import com.fasterxml.jackson.databind.*;
public class POST2GCM {
public static void post(String apiKey, Content content){
try{
// 1. URL
URL url = new URL("https://android.googleapis.com/gcm/send");
// 2. Open connection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 3. Specify POST method
conn.setRequestMethod("POST");
// 4. Set the headers
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "key="+apiKey);
conn.setDoOutput(true);
// 5. Add JSON data into POST request body
//`5.1 Use Jackson object mapper to convert Content object into JSON
ObjectMapper mapper = new ObjectMapper();
// 5.2 Get connection output stream
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
// 5.3 Copy Content "JSON" into
mapper.writeValue(wr,content);
// 5.4 Send the request
wr.flush();
// 5.5 close
wr.close();
// 6. Get the response
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 7. Print result
System.out.println(response.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The problem arises in the POST2GCM.java class, in the line
mapper.writeValue(wr,content);
Where the suggestions are to add try catch block,Add exception to method signature, Add catch clauses(s).
I did all the suggestions which did not solve the problem.
What would be the problem here?
You need to add the jackson-core-2.4.3.jar library file to your project.
Add it to your java build path too.
Of course ... 2.4.3 is the version I used, but it should work with previous versions.
Related
I'm using JSON and want to send post request to server via username, password in body and x-auth-app-id, x-auth-app-hash in header..
I have test on Postmen and it return 200 (status ok), But when I build my sources it happen error.
This is my class header:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import net.sf.json.JSONObject;
public class HttpRequestUtil {
public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
InputStream inputStream=null;
try {
URL url = new URL(requestUrl);
HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
httpUrlConn.setRequestProperty("x-auth-app-id", "6166611659356156223");
httpUrlConn.setRequestProperty("x-auth-app-hash", "a44f4ea21475fa6761392ba4bc659990bee771c413b2c207490a79f9ec78c2a61234");
httpUrlConn.setRequestProperty("Content-Type", "application/json");
httpUrlConn.setRequestMethod(requestMethod);
if ("POST".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
jsonObject = JSONObject.fromObject(buffer.toString());
}
catch (ConnectException ce) {
ce.printStackTrace();
System.out.println("Our server connection timed out");
}
catch (Exception e) {
e.printStackTrace();
System.out.println("https request error:{}");
}
finally {
try {
if(inputStream!=null) {
inputStream.close();
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return jsonObject;
}
}
And class Body:
import java.util.UUID;
import java.util.Map;
import java.util.HashMap;
import java.util.Formatter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.UnsupportedEncodingException;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
public class CallCenterController {
public static void main(String[] args) throws JSONException {
String sipUser = "vchi_dd";
String sipPassword = "m9Bp7s+CtQj85HygnIFjPn7O4Vithrunaa";
Map<String, Object> sipAccount = new HashMap<String, Object>();
sipAccount.put("sipUser", sipUser);
sipAccount.put("sipPassword", sipPassword);
sipAccount = postData(sipUser, sipPassword);
System.out.println("result: " + sipAccount);
};
public static JSONObject postData(String sipUser, String sipPassword) {
String url="https://myservice.com/oapi/v1/call/click-to-call/02437590555&sipUser="+sipUser+"&sipPassword="+sipPassword;
return HttpRequestUtil.httpRequest(url, "POST", "");
}
}
When I build it happen an exception following as:
java.io.IOException: Server returned HTTP response code: 400 for URL: https://myservice.com/oapi/v1/call/click-to-call/02437590555&sipUser=vchi_dd&sipPassword=m9Bp7s+CtQj85HygnIFjPn7O4Vithrunaa
https request error:{}
result: null
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1876)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
at com.mypackage.HttpRequestUtil.httpRequest(HttpRequestUtil.java:63)
at com.mypackage.CallCenterController.postData(CallCenterController.java:45)
at com.mypackage.CallCenterController.main(CallCenterController.java:34)
How to send correct data to my url and fix the problem?
I would use Java HTTP Client API if your java version is high enough.
Here's a link to it https://www.baeldung.com/java-9-http-client
I have used it and it feels more maintainable and clear.
Also, it seems that you're sending the request with empty body even though you say in your question that you are sending username and password in body.
And why are you adding username and password to a map if you are not using the map?
sipAccount.put("sipUser", sipUser);
sipAccount.put("sipPassword", sipPassword);
I am trying to do automate REST API through Java. For this, I am using Jersy jar.
I googled enough and was able to write a code that doesn't throw any exception. However, I am always getting 405 - Method not allowed error response when I try to reach my project's endpoint and post the request. Same endpoint returns success response on Soap UI. And there are no headers required. Media type is JSON.
Basically, I just want to do the SOAP UI operation, but through Eclipse.
PS: I'm novice, any help is appreciated.
package sample;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status.Family;
import org.glassfish.jersey.client.JerseyInvocation.Builder;
public class Sample
{
public static void main(String a[])
{
Client client = ClientBuilder.newClient();
WebTarget resource = client.target("https://endpoint-url/Resource");
Form form = new Form();
form.param("name", "bond");
form.param("ID", "007");
Builder request = (Builder) resource.request();
request.accept(MediaType.APPLICATION_JSON);
Response response = request.get();
if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL)
{
System.out.println("Success! " + response.getStatus());
System.out.println(response.readEntity(String.class));
}
else
{
System.out.println("ERROR! " + response.getStatus());
// System.out.println(response);
System.out.println(response.readEntity(String.class));
}
}
}
The issue at accept,get resource instead of Post resource
you aren't passing form parameter to resource method. That is reason getting issues.Check below
public class Sample {
public static void main(String a[])
{
Client client = ClientBuilder.newClient();
WebTarget resource = client.target("https://endpoint-url/Resource");
Form form = new Form();
form.param("name", "bond");
form.param("ID", "007");
Builder request = (Builder) resource.request();
request.accept(MediaType.APPLICATION_JSON);
Response response = request.post(Entity.entity(form,MediaType.APPLICATION_FORM_URLENCODED));
if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL)
{
System.out.println("Success! " + response.getStatus());
System.out.println(response.readEntity(String.class));
}
else
{
System.out.println("ERROR! " + response.getStatus()); // System.out.println(response);
System.out.println(response.readEntity(String.class));
}
}
}
Finally, I found the code here that worked wonders for me :)
Below is the working code:
package sample;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class JavaNetURLRESTFulClient
{
private static final String targetURL = "https://endpoint-url/Resource";
public static void main(String[] args)
{
try {
URL targetUrl = new URL(targetURL);
HttpURLConnection httpConnection = (HttpURLConnection) targetUrl.openConnection();
httpConnection.setDoOutput(true);
httpConnection.setRequestMethod("POST");
httpConnection.setRequestProperty("Content-Type", "application/json");
String input = "{\"name\":\"bond\",\"Id\":007}";
OutputStream outputStream = httpConnection.getOutputStream();
outputStream.write(input.getBytes());
outputStream.flush();
if (httpConnection.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ httpConnection.getResponseCode());
}
BufferedReader responseBuffer = new BufferedReader(new InputStreamReader(
(httpConnection.getInputStream())));
String output;
System.out.println("Output from Server:\n");
while ((output = responseBuffer.readLine()) != null) {
System.out.println(output);
}
httpConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In my web application using java, I am trying to get the page source of a web page using jersey client by passing the URL of the required page. I have been searching the web to find some good examples that would help me, but couldn't find any.
Can anybody help me with this.
Jersey is for web services. But in general, you can get the HTML source.
All these 4 varieties of jax-rs clients will print you the code:
URLConnection client
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class URLConnectionClient {
public static void main(String[] args) throws IOException {
URL restURL = new URL("http://localhost:8080/simple-service-webapp/resources/myresource/usernamepwdcontext");
URLConnection connection = (URLConnection) restURL.openConnection();
connection.setDoOutput(true);
connection.connect();
InputStreamReader ins = new InputStreamReader(connection.getInputStream());
BufferedReader in = new BufferedReader(ins);
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
in.close();
}
}
HttpConnection client
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpConnectionClient {
public static void main(String[] args) throws IOException {
URL restURL = new URL("http://localhost:8080/simple-service-webapp/resources/myresource/usernamepwdcontext");
HttpURLConnection connection = (HttpURLConnection) restURL.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(10000);
connection.connect();
InputStreamReader ins = new InputStreamReader(connection.getInputStream());
BufferedReader in = new BufferedReader(ins);
String inputLine;
while ((inputLine = in.readLine())!=null) {
System.out.println(inputLine);
}
}
}
URL stream client
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
public class URLOpenClient {
public static void main(String[] args) throws IOException {
URL restURL = new URL("http://localhost:8080/simple-service-webapp/resources/myresource/usernamepwdcontext");
InputStreamReader ins = new InputStreamReader(restURL.openStream());
BufferedReader in = new BufferedReader(ins);
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
in.close();
}
}
Jersey client.
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation.Builder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
public class URLJerseyClient {
public static void main(String[] args) {
Client cl = ClientBuilder.newClient();
WebTarget target = cl.target("http://localhost:8080/simple-service-webapp/resources/myresource/usernamepwdcontext");
target.path("resource");
Builder requestBuilder = target.request();
Response response = requestBuilder.get();
System.out.println(response.getStatus());
System.out.println(response.readEntity(String.class));
}
}
For this one you will need a dependency:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.vvirlan</groupId>
<artifactId>cert</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Client</name>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.21</version>
</dependency>
</dependencies>
</project>
4 JAX-RS clients
If your intention is just to download html code (not render it) you can do with any normal http client (or even java URLConnection classes)
Below is one ready sample I used in one of my tool. It uses apache http core 4.1.4 and apache http client 4.1.4.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class HttpUtil {
public static String getFile(String sUrl) throws ClientProtocolException, IOException{
HttpClient httpclient = new DefaultHttpClient();
StringBuilder b = new StringBuilder();
// Prepare a request object
HttpGet httpget = new HttpGet(sUrl);
// Execute the request
HttpResponse response = httpclient.execute(httpget);
// Examine the response status
System.out.println(response.getStatusLine());
// Get hold of the response entity
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if (entity != null) {
InputStream instream = entity.getContent();
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(instream));
// do something useful with the response
String s = reader.readLine();
while(s!= null){
b.append(s);
b.append("\n");
s = reader.readLine();
}
} catch (IOException ex) {
// In case of an IOException the connection will be released
// back to the connection manager automatically
throw ex;
} catch (RuntimeException ex) {
// In case of an unexpected exception you may want to abort
// the HTTP request in order to shut down the underlying
// connection and release it back to the connection manager.
httpget.abort();
throw ex;
} finally {
// Closing the input stream will trigger connection release
instream.close();
}
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
return b.toString();
}
}
I tried with Rest and also used JAR's listed in Maven repo. Which wasn't helpful.
package com.integrations;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import org.json.JSONObject;
import com.google.api.GoogleAPI;
import com.google.api.GoogleAPIException;
import com.google.api.translate.Language;
import com.google.api.translate.Translate;
public abstract class TestTranslate {
/**
* #param args
* #throws IOException
* #throws GoogleAPIException
* */
public static void main(String[] args) throws IOException {
// AIzaSyDTxHsEHG0-lVoLLJmG_PwT6L91kXiLAG0
URL obj = new URL(
"https://www.googleapis.com/language/translate/v2?key=<your api key goes here>&source=en&target=hi&q=how");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
con.setRequestProperty("content-type", "application/json; charset=UTF-8");
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
StringWriter writer = new StringWriter();
IOUtils.copy(con.getInputStream(), writer, "UTF-8");
if (responseCode == 200) {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response);
}
JSONObject org = new JSONObject(writer .toString());
JSONObject obj1 = new JSONObject(org.getJSONObject("data").getJSONArray("translations").get(0).toString());
System.out.println(obj1.getString("translatedText"));
}
enter code here
}
}
when open connection of URL by Java API it is working fine in development side,but not working on UAT,the error is showing Connection timed out.Please suggest what to do?
Here given userID,password proxyip and port are not actual because it is the client url.
package qc.los.util;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import qc.dal.DAL;
import qc.dal.dto.ParameterDTO;
import qc.los.controller.action.NewProspectAction;
import qc.sso.util.UserLockingFilter;
public class Utils {
protected static Logger log = Logger.getLogger(Utils.class);
public static void main(String[] args)
{
Utils Utilss=new Utils();
Utilss.sendVerificationCodeToCustomer("","9811937492","myTestras",true,"properhost","properport");
}
public String sendVerificationCodeToCustomer(String prospectId,String mobileNumber, String verificationCode, boolean proxyEnabled, String proxyHost, String proxyPort)
{
log.info("Start");
Properties systemSettings = System.getProperties();
try
{
//UPdated by for user id password
String urlStr ="http://www.example.com/SendSMS/sendmsg.php?uname=rahul&pass=rahul&send=Tag&dest="+mobileNumber+"&msg=Your%20verification%20code%20is%20"+verificationCode+"&concat=1";
log.info("urlStr "+urlStr);
URL u = new URL (urlStr);
log.info("proxyHost and proxyPort "+proxyHost+" "+proxyPort);
if(proxyEnabled)
{
log.info("proxyEnabled with proxyHost and proxyPort "+proxyHost+" "+proxyPort);
systemSettings.put("proxySet", "true");
systemSettings.put("proxyHost", proxyHost);
systemSettings.put("proxyPort", proxyPort);
}
HttpURLConnection con = (HttpURLConnection) u.openConnection ();
con.setDoInput(true);
con.setRequestMethod("GET");
log.info("Connection start");
con.connect();
log.info("Connection connected");
InputStream is = con.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null)
{
response.append(line);
response.append("<br>");
}
rd.close();
log.info("End:Message sucessfull with response "+response.toString());
return response.toString();
}
catch(Exception e)
{
String proxySetting = proxyEnabled + ":" + proxyHost + ":" + proxyPort;
e.printStackTrace();
log.error("exception while sending sms:("+proxySetting+")"+" "+e.getMessage());
return "exception while sending sms:("+proxySetting+")"+e.getMessage();
}
finally
{
if(proxyEnabled)
{
systemSettings.remove("proxySet");
systemSettings.remove("proxyHost");
systemSettings.remove("proxyPort");
}
log.info("End");
}
}
}