I need to send the request XML file to {url} as multipart form data. How this do in Restful web service. Before I use in there in,
RequestDispatcher rd = request.getRequestDispatcher("/file/message.jsp");
rd.forward(request, response);
But this isn't sent in specific {url}, How to sent it?
You can use the Jersey Rest Client to send your XML message as post request.
try {
Client client = Client.create();
WebResource webResource = client.resource(http://<your URI>);
// POST method
ClientResponse response = webResource.accept("multipart/form-data").type("multipart/form-data").post(ClientResponse.class, "<your XML message>");
// check response status code
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}
// display response
String output = response.getEntity(String.class);
System.out.println("Output from Server .... ");
System.out.println(output + "\n");
} catch (Exception e) {
e.printStackTrace();
}
For Jersey Client you can find documentation here:
Jersey REST Client
WebResource
If you can do it (depends on your context), using a JAX-RS client is a solution.
Example with Apache CXF :
InputStream inputStream = getClass().getResourceAsStream("/file/message.jsp");
WebClient client = WebClient.create("http://myURL");
client.type("multipart/form-data");
ContentDisposition cd = new ContentDisposition("attachment;filename=message.jsp");
Attachment att = new Attachment("root", inputStream, cd);
client.post(new MultipartBody(att));
I don't think web service is best choice for you you can try native stream and then you can write the header and the body as you like here is sample code to explain my point
Socket socket=new new socket(InetAddress.getByName("stackoverflow.com"), 80);
// just the host and the port
Writer out = new OutputStreamWriter(socket.getOutputStream(),"UTF-8");
out.write("POST http://" + HOST + ":" + port+ "/ HTTP/1.1\r\n");//here u can insert your end point or the page accepts the xml msg
out.write("Host: " + HOST + "/ \r\n");
out.write("Content-type: application/xml,text/xml\r\n");// Accept
out.write("Content-length: " + req.length() + "\r\n");
out.write("Accept:application/xml,text/xml\r\n");
out.write("\r\n");
// req the Request Body or the xml file to be sent
out.write(req);//
out.flush();`
Related
I added an open extension to an event in a calendar and am trying to read it back.
Here is the url:
https://graph.microsoft.com/v1.0/users/{userid}/calendars/{calendarId}=/events?$expand=Extensions($filter=Id eq 'c.i.m.p.server.entities.outlook.Event')
I cannot get this to work in a Java program. The following combinations do work:
It works my Java program if I remove the $expand... parameter. I can also ask for certain fields, that works too.
The request works in Postman (I just have to set the token)
The request works in Graph Explorer when I log in as the owner of the calendar
Here is the extension (inside one of the events) when I use Postman to read the event. It is the last item in the event:
"extensions#odata.context": "https://graph.microsoft.com/v1.0/$metadata#users('{userid}')/calendars('{calendarId}')/events('{eventId})/extensions",
"extensions": [
{
"#odata.type": "#microsoft.graph.openTypeExtension",
"id": "Microsoft.OutlookServices.OpenTypeExtension.c.i.m.p.server.entities.outlook.Event",
"extensionName": "c.i.m.p.server.entities.outlook.Event",
"adherentId": "12346",
"timeSlotID": "346463"
}
]
Here is the Java code (Java 8, using java.io and java.net libraries):
private static void doSomething(String _accessToken) throws IOException {
String urlString = "https://graph.microsoft.com/v1.0/users/{userId}/calendars/{calendarId}/events?$expand=Extensions($filter=Id eq 'c.i.m.p.server.entities.outlook.Event')";
URL url = new URL(urlString);
Proxy webProxy
= new Proxy(Proxy.Type.HTTP, new InetSocketAddress({proxy-address}, {port}));
HttpURLConnection connection = (HttpURLConnection) url.openConnection(webProxy);
// Set the appropriate header fields in the request header.
connection.setRequestProperty("Authorization", "Bearer " + _accessToken);
connection.setRequestProperty("Accept", "application/json");
connection.setDoOutput(true);
connection.setReadTimeout(5000);
connection.setRequestMethod(HttpMethod.GET);
try {
connection.connect();
int responseCode = connection.getResponseCode();
System.out.println("execute(), response code = " + responseCode);
String responseMessage = connection.getResponseMessage();
System.out.println("execute(), response Message = " + responseMessage);
String responseString = null;
try {
InputStream ins = connection.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(ins));
StringBuffer sb=new StringBuffer();
String line;
while ((line=br.readLine()) != null) {
sb.append(line);
}
responseString = sb.toString();
} catch (Exception e) {
System.out.println("Could not get input stream from response, error is " + e.toString());
}
System.out.println("execute(), httpResult = " + responseString);
} catch (IOException e) {
System.out.println(".execute(), IOException : " + e.toString());
} finally {
connection.disconnect();
}
}
How do I fix this? Thanks!
400 means bad request. It could be because of url encoding. Url encode the query string.
Something like
String query = "Extensions($filter=Id eq 'c.i.m.p.server.entities.outlook.Event'";
String url = "https://graph.microsoft.com/v1.0/users/{userId}/calendars/{calendarId}/events?
$expand=" + URLEncoder.encode(query, StandardCharsets.UTF_8.name());
Alternatively you could use graph service java api based on your need which will help abstract all the interactions for you or you could use any of the rest clients available.
First of all, you should provide more info on the error - Stacktrace and error message. But 400 code indicates that was a user mistake, meaning that you are sending an invalid request. Since you say that postman request works then compare all the headers that are sent by postman and see if your code misses some hearer. As for the code, instead of coding your own Http client functionality I would suggest using 3d party Http client. Here are a few suggestions:
Apache Http client - very popular and well known 3d party Http Client
OK Http client - Open-source Http client. Here is tutorial
MgntUtils Http client - very simple 3d party HttpClient: Provided in MgntUtils Open source library (written by me). Very simple in use. Take a look at Javadoc. Library itself provided as Maven artifacts and on Git (including source code and Javadoc).
I have been working on integrating my application with LinkedIn by following the documentation located here. I have created my application in LinkedIn and am able to successfully retrieve the authorization code but I am getting the following error when trying to get the access token :
{"error_description":"missing required parameters, includes an invalid
parameter value, parameter more than once. : Unable to retrieve access token : appId or redirect uri does not match authorization code or authorization code expired","error":"invalid_request"}
I have verified the following to be true:
The redirect uri is the same for the authorization request and access token request
I am using the authorization code within 20 seconds of it being issued.
I am including "Content-Type:application/x-www-form-urlencoded" in the request header
Some things I have tried with no success:
Posting the request with the parameters as part of the url
Posting the request with parameters as part of the body
sending the redirect uri as both encoded and plain text
using a get request instead of a post.
Here is my current code:
linkedin_access_token_url = "https://www.linkedin.com/uas/oauth2/accessToken?"+
"grant_type=authorization_code"+
"&code="+ authCode
+ "&redirect_uri=https://localhost:8090/ProfileSetup/linkedInAuth.jsp
+ "&client_id=" + linkedin_client_id
+ "&client_secret=" + linkedin_client_secret;
HttpClient http = new DefaultHttpClient();
HttpPost httppost = new HttpPost(linkedin_access_token_url);
try {
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
HttpResponse response = http.execute(httppost);
HttpEntity entity = response.getEntity();
System.out.println("status code " +
response.getStatusLine().getStatusCode());
System.out.println("statusreason"+
response.getStatusLine().getReasonPhrase());
InputStream stream = entity.getContent();
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(stream));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (Exception e) {
}
String resp = sb.toString();
System.out.println("response " + resp);
} catch (Exception ex) {
System.out.println("linked in HttpResponse Error: " + ex);
} finally {
httppost.releaseConnection();
}
And the authorization url (actual client id is sent in place of linkedin_client_id):
https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=linkedin_client_id&redirect_uri=https://localhost:8090/ProfileSetup/linkedInAuth.jsp&state=0kcmjj5504tpgb9&scope=r_basicprofile
Does anyone see what I am doing wrong? If I take this compiled url and paste it in the browser, I am able to retrieve an access token without any issue. Is there a problem with my request?
Looks like you are including all of the parameters for the request as attributes in the URL, rather than in the POST body as x-www-form-urlencoded elements.
Check out this other Stack thread for details on how to send the values in the request body rather than as URL attributes:
Sending HTTP POST Request In Java
I was finally able to figure out what was wrong with my app. My local environment was not configured correctly for https. Moving the code onto our dev box set up with https fixed the issue.
How to create an issue in Jira using the REST API? I have tried the examples using curl. But I need to create defect in Eclipse using Java and REST API.
You want to integrate JIRA into Eclipse?
See: https://confluence.atlassian.com/display/IDEPLUGIN/Working+with+JIRA+Issues+in+Eclipse
You want a custom application to create tickets automagically?
Probably you'll need a REST client using the jersey-client artifact, I think this is the easiest way.
Firstly, check out the REST API documentation: https://docs.atlassian.com/jira/REST/latest/
With the POST method you can push a JSON object depiciting a wannabe issue to the JIRA server. You just have to exactly know what fields you can and should fill in. If you send fields that are not on the create issue screen, or is required but you haven't specified them, you'll get an error.
You can find an example here: http://pastebin.com/JeucUZNG
Try this code
public static String invokePostMethod() throws AuthenticationException, ClientHandlerException, IOException
{
Client client = Client.create();
WebResource webResource = client.resource("http://localhost:8080/rest/api/latest/issue");
String data = "{"fields":{"project":{"key":"DEMO"},"summary":"REST Test","issuetype":{"name":"Bug"}}}";
String auth = new String(Base64.encode(Uname + ":" + Password));
ClientResponse response = webResource.header("Authorization", "Basic " + auth).type("application/json").accept("application/json").post(ClientResponse.class, data);
int statusCode = response.getStatus();
if (statusCode == 401) {
throw new AuthenticationException("Invalid Username or Password");
} else if (statusCode == 403) {
throw new AuthenticationException("Forbidden");
} else if (statusCode == 200 || statusCode == 201) {
System.out.println("Ticket Create succesfully");
} else {
System.out.print("Http Error : " + statusCode);
}
// ******************************Getting Responce body*********************************************
BufferedReader inputStream = new BufferedReader(new InputStreamReader(response.getEntityInputStream()));
String line = null;
while ((line = inputStream.readLine()) != null) {
System.out.println(line);
}
return response.getEntity(String.class);
}
try {
Client client = Client.create();
client.addFilter(new HTTPBasicAuthFilter("username", "password"));
String input = "{\"fields\":{\"project\":{\"key\":\"DEMO\"},\"summary\":\"REST Test\",\"description\": \"Creating of an issue using project keys and issue type names using the REST API\",\"issuetype\":{\"name\":\"Bug\"}}}";
WebResource resource = client.resource("http://localhost:8080/rest/api/2/issue");
ClientResponse response = resource.type("application/json").accept("application/json").post(ClientResponse.class,input);
if (response.getStatus() != 201) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
System.out.println("Output from server");
System.out.println(response.getEntity(String.class));
} catch (Exception e) {
e.printStackTrace();
}
For more info:
https://docs.atlassian.com/jira/REST/cloud/#api/2/issue-createIssue
http://www.j-tricks.com/tutorials/java-rest-client-for-jira-using-jersey
There is a service endpoint and an xsd file for SOAP request. But, there is no wsdl file. How can I generate soap request (xml request as a string ) manually from this and send it to the service endpoint?
I found similar answer on SO. But it's for C# and .NET. Any idea for Java will be highly appreciated.
Take a look at [JAXB]: https://jaxb.java.net/
It does stuff like you are asking. It generates java classes if needed:
the command xjc is the key for generation
Here is an example from an old project of mine connecting to a SharePoint web service. It should show you all the basics that you need.
try {
URL sharepoint = new URL("http://server.com/_vti_bin/Lists.asmx");
URLConnection sharepoint_connection = sharepoint.openConnection();
String body = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
" <soap:Body>" +
" </soap:Body>" +
"</soap:Envelope>";
System.out.println("~~~~~ Roadmap: " + body);
sharepoint_connection.setRequestProperty("Man", "POST /_vti_bin/Lists.asmx HTTP/1.1");
sharepoint_connection.setRequestProperty("Host", "server.com");
sharepoint_connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
sharepoint_connection.setRequestProperty("Content-Length", Integer.toString(body.length()));
sharepoint_connection.setRequestProperty("SOAPAction", "http://schemas.microsoft.com/sharepoint/soap/GetListItems");
// Write request body to SharePoint
sharepoint_connection.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(sharepoint_connection.getOutputStream());
writer.write(body);
writer.close();
//sharepoint_connection.connect();
// Read result from SharePoint
BufferedReader reader = new BufferedReader(new InputStreamReader(sharepoint_connection.getInputStream()));
String inputLine;
while ((inputLine = reader.readLine()) != null)
xmltext += inputLine;
reader.close();
} catch (MalformedURLException e) { // new URL() failed
} catch (IOException e) { // openConnection() failed
}
I am using Apache client libs for http client to post some data to my server.
Below is the code, I get the status line response, but I am not getting the contents.
But on wireshark I could see server is responding the with few contents, such content type, location etc. for my code I am getting the following output.
Status :: HTTP/1.1 201 Created Content null
Pls help me to find out where I have gone wrong to read the content , do I need to some proxy related settings ?
HttpClient client = new DefaultHttpClient();
String line = ""; String status = "";
HttpPost post = new HttpPost("http://127.0.0.1/msg");
try {
HttpEntity e = new StringEntity("POSTING TO SERVER FOR TESTING");
post.setEntity(e);
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new
InputStreamReader(response.getEntity().getContent()));
status = response.getStatusLine().toString() ;
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(" Status :: "+ status + " Content " + line);
The reason for Status :: HTTP/1.1 201 Created Content null is because the last value assigned to line is null (it's how you broke out of the loop). The response may not have any content. You can use the API to examine the headers as you need
Take a look at How to get headers? (java,httpclient 4.X) for an example