400 Bad request in J2me - http

I am trying to hit .svc service from my JME application using POST method. but getting 'bad request'. Following is my code.
HttpConnection hc = (HttpConnection) Connector.open(url, Connector.READ_WRITE);
hc.setRequestMethod(HttpConnection.POST);
hc.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0" );
hc.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
hc.setRequestProperty("Content-Length", ""+(postMsg.getBytes().length));
out = hc.openOutputStream();
out.write(postMsg.getBytes());
System.out.println("hc.getResponseCode() = "+hc.getResponseCode()+ " hc.getResponseMessage() = "+hc.getResponseMessage());
Please tell me what is wrong with the code.

Instead of http, I used Ksoap2-j2me-core jar with following code that i found -
SoapObject request = new SoapObject("namespace", "login");
request.addProperty("username", "pranav");
request.addProperty("password", "gangan");
//create the SOAP envelope
final SoapSerializationEnvelope env = new SoapSerializationEnvelope(SoapEnvelope.VER11);
env.setOutputSoapObject(request);
//create the transport and then call
final HttpTransport httpTransport = new HttpTransport("http://URL");
httpTransport.call("\"login\"", env);
SoapObject body = (SoapObject) env.bodyIn;
//body.getProperty(0) will return the content of the first tag inside body
Object response = body.getProperty(0);
System.out.println(response.toString);

Related

RestTemplate request with braces ("{", "}")

I want to send request through RestTemplate. But my url has braces ('{', '}'), and therefore I have exception: "Not enough variable values available to expand ...".
I try do it through uri
UriComponentsBuilder builder = UriComponentsBuilder.fromPath(url);
UriComponents uriComponents = builder.build();
URI uri = uriComponents.toUri();
But I got new exception:"protocol = https host = null".
How I can send request with my URL? In URL must be braces.
My code:
String url = "https://api.vk.com/method/execute?code=return[API.users.search({"count":1})];&access_token...
String result = restTemplate.getForObject(url, String.class);
Below code encrypts the uri using UriComponentsBuilder, adds query params using RestTemplate and also sets HttpHeaders if any.
public HttpEntity<String> getEntityByUri() {
String req = "https://api.vk.com/method/execute";
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(req)
.queryParam("code",
"return[API.users.search({"count":1})]");
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.ALL));
HttpEntity<String> httpEntity = new HttpEntity<String>(headers);
return new RestTemplate().exchange(builder.build().encode().toUri(), HttpMethod.GET, httpEntity, String.class);
}
Hope this helps and good luck!

MarkLogic spring RestTemplate

Hi I am trying to get the list of graphs in MarkLogic using RestTemplate.
Below is the sample code. From the browser I can able to get the graph list, but through the Java REST Client I am getting error 401.
HttpHeaders header = new HttpHeaders();
String plainCreds = "restadmin:restpassword";
byte[] plainCredsBytes = plainCreds.getBytes();
byte[] base64CredsBytes = Base64.encode(plainCredsBytes);
String base64Creds = new String(base64CredsBytes);
header.setAccessControlAllowCredentials(true);
header.add("Authorization", "Basic " + base64Creds);
header.setAccept(Arrays.asList(MediaType.TEXT_XML));
header.setContentType(MediaType.TEXT_XML);
HttpEntity<String> entity = new HttpEntity<String>(header);
String url = "http://localhost:8003/v1/graphs";
ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
System.out.println("Response : "+response.getStatusCode());
Please help me in resolving the issue
Try copying the HTTP auth code at https://github.com/rjrudin/ml-app-deployer/blob/master/src/main/java/com/rjrudin/marklogic/rest/util/RestTemplateUtil.java#L18 - I know it will handle HTTP basic auth against the management API on port 8002, and it should work fine on your REST API server on port 8003.

Mule HTTP endpoint with parameters

I'm trying to write a Mule flow to poll a CRUD-web service. I've managed to do kind of what I'd like to do with a small JAVA-application but I'd like to use a HTTP-endpoint in a mule flow instead if its possible.
I'd like to do a HTTP-GET-request with Database ID in the HTTP-HEADER. Is this possible with a MULE-inbound-endpoint?
// HTTP GET request
private void sendGet() throws Exception {
String url = "https://XXXXXXXXXXXXXXXXXXXXXXXXXX";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
con.setRequestProperty("X-Appery-Database-Id", "XXXXXXXXXXXXXXXXXX");
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
You can use MuleClient to execute a set of tests (CRUD operations), for example:
MuleClient client = muleContext.getClient();
Map parameters = new HashMap();
parameters.put("Content-Type", "application/json");
parameters.put("http.method", "GET"); // or POST, DELETE, PUT
parameters.put("DatabaseID", "ID");
then send to http-inbound-endpoint
MuleMessage response = client.send("http://localhost:8091/rest/domain", PAYLOAD, parameters);
assertNotNull(response);
assertThat(Integer.valueOf(response.getInboundProperty(HTTP_STATUS).toString()), is(200));
Victor shows you how to do it from a flow. I hope to help.
It is possible, the following:
<poll>
<http:outbound-endpoint exchange-pattern="request-response" host="localhost" port="8081" method="GET">
<set-property propertyName="X-Appery-Database-Id" value="XXXXXXXXXXXXXXXXXX" />
<set-property propertyName="User-Agent" value="MY_USER_AGENT" />
</http:outbound-endpoint>
</poll>
will generate a request like this:
GET / HTTP/1.1
X-MULE_ENDPOINT: http://localhost:8081
X-Appery-Database-Id: XXXXXXXXXXXXXXXXXX
X-MULE_ROOT_MESSAGE_ID: 8c80b9f0-7682-11e4-94ea-12a3ae03ce3a
User-Agent: MY_USER_AGENT
X-MULE_SESSION: rO0ABXNyACNvcmcubXVsZS5zZXNzaW9uLkRlZmF1bHRNdWxlU2Vzc2lvbi7rdtEW7GGKAwAFWgAFdmFsaWRMAA1mbG93Q29uc3RydWN0dAAmTG9yZy9tdWxlL2FwaS9jb25zdHJ1Y3QvRmxvd0NvbnN0cnVjdDtMAAJpZHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wACnByb3BlcnRpZXN0AA9MamF2YS91dGlsL01hcDtMAA9zZWN1cml0eUNvbnRleHR0ACdMb3JnL211bGUvYXBpL3NlY3VyaXR5L1NlY3VyaXR5Q29udGV4dDt4cAFwdAAkOGM4MGI5ZjEtNzY4Mi0xMWU0LTk0ZWEtMTJhM2FlMDNjZTNhc3IAJWphdmEudXRpbC5Db2xsZWN0aW9ucyRTeW5jaHJvbml6ZWRNYXAbc/kJS0s5ewMAAkwAAW1xAH4AA0wABW11dGV4dAASTGphdmEvbGFuZy9PYmplY3Q7eHBzcgAkb3JnLm11bGUudXRpbC5DYXNlSW5zZW5zaXRpdmVIYXNoTWFwndHZ72dFzgADAAB4cHcMP0AAAAAAABAAAAAAeHEAfgAJeHB4
Host: localhost:8081

Apache Abdera Multipart Request throwing nullpointer Exception(IBM connection API)

I am using Apache abdera to post multipart request to IBM connection 4.0 API. I am getting nullpointer exception from Abdera API. Please let me know what's the root cause.
private void createEntryWithAttachment(){
try {
String activityId = "urn:lsid:ibm.com:oa:662d0dc7-0308-48ee-8291-d730c733d2d1";
String activityIdLocal = activityId.substring(activityId.lastIndexOf(":")+1, activityId.length());
String createEntryLocal = createEntry+activityIdLocal;
Abdera abdera = new Abdera();
AbderaClient client = new AbderaClient(abdera);
AbderaClient.registerTrustManager();
System.out.println("pd --->"+pd);
client.addCookie("poktam2cl.iespc.ibm.com", "PD-S-SESSION-ID", pd, "/", null, true);
RequestOptions requestOptions = client.getDefaultRequestOptions();
requestOptions.setUseChunked(true);
requestOptions.setHeader("Connection", "close");
requestOptions.setHeader("Content-Type", "multipart/related;type=\"application/atom+xml\"");
requestOptions.setContentType("multipart/related;type=\"application/atom+xml\"");
requestOptions.setSlug("Sample.txt");
Credentials credentials = new UsernamePasswordCredentials(username, password);
client.addCredentials(createEntryLocal, AuthScope.ANY_REALM,AuthScope.ANY_SCHEME, credentials);
Entry entry = abdera.getFactory().newEntry();
entry.setTitle("create entry with attachment title ");
entry.setContent("create entry with attachment content");
javax.xml.namespace.QName field = new QName("http://www.ibm.com/xmlns/prod/sn", "field", "snx");
org.apache.abdera.model.Element fieldElement = entry.addExtension(field);
fieldElement.setAttributeValue("type", "file");
fieldElement.setAttributeValue("name", "sampletextfile1");
fieldElement.setAttributeValue("position", "3000");
FileInputStream fis = new FileInputStream(filepath);
requestOptions.setHeader("Content-Length", "35");
entry.addCategory("http://www.ibm.com/xmlns/prod/sn/type","entry", "Entry");
ClientResponse response = client.post(createEntryLocal, entry, fis, "multipart/related;type=\"application/atom+xml\"", requestOptions );
System.out.println("Entry Created with attachment's resp: " + response.getStatus());
if(response.getStatus() == 201){
System.out.println("Entry Created with attachment successfully .....");
printIBMConnectionErrorMessage(response);
}else{
System.out.println("Entry with attachment creation failed");
printIBMConnectionErrorMessage(response);
//System.exit(0);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Output
java.lang.NullPointerException
at org.apache.abdera.protocol.client.util.MultipartRelatedRequestEntity.writeInput(MultipartRelatedRequestEntity.java:74)
at org.apache.abdera.protocol.client.util.MultipartRelatedRequestEntity.writeRequest(MultipartRelatedRequestEntity.java:59)
at org.apache.commons.httpclient.methods.EntityEnclosingMethod.writeRequestBody(EntityEnclosingMethod.java:499)
at org.apache.commons.httpclient.HttpMethodBase.writeRequest(HttpMethodBase.java:2114)
at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:1096)
at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:398)
at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:323)
at org.apache.abdera.protocol.client.AbderaClient.execute(AbderaClient.java:688)
at org.apache.abdera.protocol.client.AbderaClient.post(AbderaClient.java:306)
at JavaAgentEntryWithAttachment.createEntryWithAttachment(JavaAgentEntryWithAttachment.java:157)
at JavaAgentEntryWithAttachment.main(JavaAgentEntryWithAttachment.java:66)
This exception is coming from abdera API, class called MultipartRelatedRequestEntity.java, Line no 74. I have placed line no 74 source code below. So its clear that contentSrc is null & Abdera API not allowing me to set this value. Please let me know what I am missing here.
String contentId = entry.getContentSrc().toString();
I did in two steps:
Send the file
Call to update the data
Each with the good mime type. You can not send the file with XML mime type. And put the length of the file.
It is possible to avoid the nullpointer and do it in one request. I had the same issue and created another issue and managed to find a solution. You can find it here.
It comes down to the following code example where you create a HttpClient Part which can contain a StringPart and a FilePart
final Entry entry = // ... Create your Entry
final RequestOptions options = this.client.getDefaultRequestOptions();
options.setHeader("Content-Type", "multipart/related;type=\"application/atom+xml\"");
StringPart entryPart = new StringPart("entry", entry.toString());
entryPart.setContentType("application/atom+xml");
FilePart filePart = new FilePart("file", new File(resource.getFile()));
RequestEntity request = new MultipartRequestEntity(new Part[] { entryPart, filePart}, this.client.getHttpClientParams());
ClientResponse response = client.post(this.url + this.activityId, request, options);
Hope this will help people in the future if they are using Abdera.

Consuming REST Service pb

I'm having some problem consuming REST Service and want to figure out what I'm missing in implementation.
https://<server-name-or-address>/api/sessions
if I call this rest api using cURL, it works just fine by following script
curl -i -k -H "Accept:application/*+xml;version=1.5" -u username:password -X POST https://<server-name-or-address>/api/sessions
However, it isn't working at all with C# asp.net. I'm not sure what I'm missing here. Here are my attempts:
1) Using HTTP Web Request
Uri address = new Uri(url);
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
request.Method = "POST";
request.Accept = "application/*+xml;version=1.5";
request.Credentials = new NetworkCredential(username,password);
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
// following exception fires on calling aforementioned statement
The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
2) Using Hammock.net
Hammock.RestClient client = new Hammock.RestClient();
string encodedAPIKey = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", username, password)));
client.AddHeader("Accept", "application/*+xml;version=1.5");
client.AddHeader("Authorization", "Basic " + username + ":" + password);
client.Authority = url;
Hammock.RestRequest req = new Hammock.RestRequest();
req.Path = url;
Hammock.RestResponse response = client.Request(req);
string _result = client.Request(req).Content; // exception
3) Using RestSharp
string _loginInfo = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", username, password)));
RestSharp.RestClient client = new RestSharp.RestClient();
client.AddDefaultHeader("Accept", "application/*+xml;version=1.5");
client.AddDefaultHeader("Authorization", "Basic " + _loginInfo);
client.BaseUrl = url;
RestSharp.RestRequest request = new RestSharp.RestRequest();
request.AddUrlSegment("method", "POST");
request.AddUrlSegment("uri", url);
string result = client.Execute(request).Content;
I also have tried with HttpClient, WebRequest, WebClient though nothing appears to work.
Try manually setting the Authorization header yourself in the HTTP request.
string credentials = String.Format("{0}:{1}", username, password);
byte[] bytes = Encoding.ASCII.GetBytes(credentials);
string base64 = Convert.ToBase64String(bytes);
string authorization = String.Concat("Basic ", base64);
request.Headers.Add("Authorization", authorization);
EDIT:
It looks as though it may be due to a self-signed, expired, or otherwise invalid cert. Try the following
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
Gleaned from this SO: https://stackoverflow.com/questions/5595049/servicepointmanager-servercertificatevalidationcallback-question

Resources