when i try to execute this alfresco webscript [http://localhost:8383/alfresco/service/get-order-info] through Advance REST client (google chrome add-on) then it works smoothly but when i try to execute by following code then it gives error at this line JSONObject jsonObject = (JSONObject) new JSONParser().parse(responseString);
public class ComplainMasterDaoImpl implements ComplainMasterDao
{
#Override
public ComplainMaster fetchComplainInfo(String orderId, String user) throws Exception
{
// TODO Auto-generated method stub
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://localhost:8383/alfresco/service/get-order-info");
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
formParams.add(new BasicNameValuePair("orderId", orderId));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formParams, "UTF-8");
httpPost.setEntity(formEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
String responseString = IOUtils.toString(httpEntity.getContent(), "UTF-8");
JSONObject jsonObject = (JSONObject) new JSONParser().parse(responseString);
JSONObject resultJson = (JSONObject) jsonObject.get("result");
System.out.println(resultJson.toString());
return null;
}
}
and when i debugged it then i got resonseString like Apache Tomcat/6.0.29 - Error report HTTP Status 401 - type Status reportmessage description This request requires HTTP authentication ().Apache Tomcat/6.0.29
content of get-order-info.post.desc.xml :
<webscript>
<shortname>Get Order Information</shortname>
<description>Used to create complain</description>
<url>/get-order-info</url>
<format default="json"> </format>
<authentication>user</authentication>
</webscript>
Double check your description file. and check which level of authentication you want to provide while web script development.
In webscript desc.xml file, authentication (optional) is the required level of authentication; valid values are:
none: specifies that no authentication is required at all
guest: specifies that at least guest authentication is required
user: specifies that at least named user authentication is required
admin: specifies that at least a named admin authentication is required
Note: if not specified, the default value is none
Note: The optional runas attribute can be used to force the execution of a web script as a specific user. This can only be specified for web scripts that are stored in the Java Class path.
refer the following link for more details:
http://wiki.alfresco.com/wiki/Web_Scripts
Or else if you want to keep your web script for only authenticated users, then you need to pass required authentication details for the user who is accessing the web script from struts. But make sure that the user must exists in alfresco.
So, add following code in your fetchComplainInfo method for basic authentication:
String basic_auth = new String(Base64.encodeBase64((YOUR_USER_NAME+":"+YOUR_PASSWORD).getBytes()));
httpPost.addHeader("Authorization", "Basic " + basic_auth);
So, your method will be like this:
public class ComplainMasterDaoImpl implements ComplainMasterDao
{
#Override
public ComplainMaster fetchComplainInfo(String orderId, String user) throws Exception
{
// TODO Auto-generated method stub
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://localhost:8383/alfresco/service/get-order- info");
String basic_auth = new String(Base64.encodeBase64((YOUR_USER_NAME+":"+YOUR_PASSWORD).getBytes()));
httpPost.addHeader("Authorization", "Basic " + basic_auth);
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
formParams.add(new BasicNameValuePair("orderId", orderId));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formParams, "UTF-8");
httpPost.setEntity(formEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
String responseString = IOUtils.toString(httpEntity.getContent(), "UTF-8");
JSONObject jsonObject = (JSONObject) new JSONParser().parse(responseString);
JSONObject resultJson = (JSONObject) jsonObject.get("result");
System.out.println(resultJson.toString());
return null;
}
}
Well my guess is that you are authenticated in alfresco in another tab of google chrome and that alfresco picks that up. 401 is an authentication exception and you need to authenticate to alfresco which is not done in your code above. See for example:
http://wiki.alfresco.com/wiki/Web_Scripts#Authenticating
The first thing you should do is to check you webscripts description file to find out which authentication method it demands. Since this seems to be a custom webscript in you alfresco installation its hard to tell you where it is to be found. It could be called something like get-order.info.post.desc.xml (strange with a post request to a script named get- BTW) Look at the authentication element.
Related
Can someone guide me how to test iOS(auto-renewable IAP) Receipt Validation API by using Sandbox URL?
I have tried this below snippet.
public void validateReceiptData(VerifyReceiptRequestView requestview) {
System.out.println("validateReceiptData ....................");
String VERIFICATION_URL=" https://sandbox.itunes.apple.com/verifyReceipt";
HttpClient httpClient = new DefaultHttpClient();
try {
HttpPost request = new HttpPost(VERIFICATION_URL);
JSONObject requestData = new JSONObject();
requestData.put("receipt-data", requestview.getReceiptdata());
requestData.put("password", requestview.getPassword());
StringEntity requestEntity = new StringEntity(requestData.toString());
request.addHeader("content-type", "application/x-www-form-urlencoded");
request.setEntity(requestEntity);
HttpResponse response =httpClient.execute(request);
String responseBody = EntityUtils.toString(response.getEntity());
JSONObject responseJSON = new JSONObject(responseBody);
System.out.println("responseJSON -------------->"+responseJSON);
}catch(Exception e) {
e.printStackTrace();
}
}
But I need sample request data for the below mentioned fields
requestData.put("receipt-data", requestview.getReceiptdata());
requestData.put("password", requestview.getPassword());
Does the field requestview.getReceiptdata() requires any Valid Purchased receipt or does Apple provides any sample receipt data to test this API in SandBox environment.
So I've got this code:
HttpClient httpClient = new DefaultHttpClient();
try {
HttpPost request = new HttpPost("url");
StringEntity params = new StringEntity("stuff");
request.addHeader("content-type", "application/json");
//request.addHeader("Accept","application/json");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
//stuff
} catch (Exception ex) {
//stuff
} finally {
httpClient.getConnectionManager().shutdown();
}
I need to create a POST request which I can do with curl -X POST /groups/:group_id/members/add etc but I'm not sure how to add the /groups/ param to my code... I'm not super familiar with how to do this so any advice would be appreciated. Thanks!
EDIT 1: (SOLVED)
Have used the suggested code but would like some help with variables used in the string while remaining valid JSON format, if possible.
EDIT 2:
Using that method, can you show an example of how to add multiple users to that one StringEntity? So like user1 is "User1" and has the email "Email1" and user2 has "User2" and "Email2" etc
Just create a url string using the prams you have and pass it as argument to HttpPost()
DefaultHttpClient httpClient = new DefaultHttpClient();
String groupId = "groupId1";
String URL = "http://localhost:8080/"+groupId+"/members/add"
HttpPost postRequest = new HttpPost(
URL );
StringEntity input = new StringEntity("{\"name\":matt,\"from\":\"stackovefflow\"}");
input.setContentType("application/json");
postRequest.setEntity(input);
HttpResponse response = httpClient.execute(postRequest);
UPDATED
The input to StringEntity is a string whihc you can manipulate in any way.
You can define a method like
private createStringEntity(String name, String email){
return new StringEntity("{\"name\":\""+name+"\",\"email\":\""+email+"\"}");
}
The "/groups/..." part is not a parameter but a fraction of the url. I dont think this will work, because "url" is just a String, change it to this:
HttpPost request = new HttpPost("http://stackoverflow.com/groups/[ID]/members/add");
I'm using the following code to send a http request to github.
String url = "https://api.github.com/repositories";
try {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost request = new HttpPost(url);
// StringEntity params = new StringEntity(body);
request.addHeader("content-type", "application/json");
// request.setEntity(params);
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
System.out.println(json);
} catch (IOException ex) {
}
I got output: {"message":"Not Found","documentation_url":"https://developer.github.com/v3"}
If use directly put "https://api.github.com/repositories" in browser, a lot of useful information will be shown. My question is how can I get the information I see when using browser by using Java.
You should use HttpGet instead of HttpPost. Just like your browser sends a GET request.
Hi iam creating an android application. In my application i have some form fields like edittext and radio buttons i am creating a JSONObject by retrieving text from all the form fields. JsonObject is created successfully. Now i want to pass this object to my PHP page where i have written code for getting this details and storing it in database. My problem is i am not understanding how to send this JSON object through httpPost or httpGet method. Only way i know is send parameters through List<NameValuePair> so i'm trying to convert JSONObject to List<NameValuePair>. Can anybody provide a method which can directly convert my JSONObject to List<NameValuePair>. Is there any predefined method for doing this. Or can any one provide solution where i can directly send by JSONObject to PHP and retrieve there.
Pass your JSONObject as a string to the String Entity constructor and then pass it to setEntity()
Sample:
HttpPost request = new HttpPost("//website");
StringEntity params =new StringEntity("passmyjson=" + yourJSONOBject.toString());
request.addHeader("content-type", "//header");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
in php File to check that it works;
<?php
print_r($_POST);
$json_string = $_POST['passmyjson'];
$json = json_decode($json_string);
print_r($json);
?>
You can do that with Apache HttpClient. I assume you have already a PHP handler that handles this request. Simply,
Create your JSONObject
Put your desired values
Send that json to php handler
You need to send request as application/x-www-form-urlencoded
Let's call url : http://your_php_service.com/handleJson;
HttpClient httpClient = new DefaultHttpClient();
JSONObject json = new JSONObject();
json.put("key", "val");
try {
HttpPost request = new HttpPost("http://your_php_service.com/handleJson");
StringEntity params = new StringEntity("json=" + json.toString());
request.addHeader("content-type", "application/x-www-form-urlencoded");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
} catch (Exception ex) {
} finally {
httpClient.getConnectionManager().shutdown();
}
The format of request param will be ;
json={"key": "val"}
And you can handle this on php side like;
<?php
.....
$json = $_POST["json"]; // This will be json string
.....
Thank you all i got it
I added the following lines to my android Activity class
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse;
HttpPost httppost = new HttpPost(link); //-->link is the php page url
httppost.setEntity(new StringEntity(obj.toString())); //-->obj is JSONObject
httpResponse = httpClient.execute(httppost);
HttpEntity httpEntity = httpResponse.getEntity();
and in my php file i have added the following code
$msg=json_decode(file_get_contents('php://input'), true);
To get particular value from recieved Json string i added this $data = $msg['name'] ;
It is working
So there is this website that has a login form. I want to log in and then download a file. When submitting the form, not only do username and password get transmitted in the http POST but also a token that is in a hidden <input> tag.
Now, my Problem is that whenever I open the URL in java and get the token to make a POST the token is invalid when I use a HttpClient.
I somehow need to use the same client for calling the website to get the token and making the post. Unfortunately I get a 403 FORBIDDEN return code when trying to access the file.
This is what I have so far:
public static void main(String[] args){
try {
String token = getTokenFromPage("http://my.url");
HttpContext context = new BasicHttpContext();
DefaultHttpClient client = new DefaultHttpClient();
List <NameValuePair> parameters = new ArrayList <NameValuePair>();
HttpPost post = new HttpPost("http://my.url");
parameters.add(new BasicNameValuePair("username", "MYNAME"));
parameters.add(new BasicNameValuePair("password", "MYPW"));
parameters.add(new BasicNameValuePair("token", token));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, HTTP.UTF_8);
post.setEntity(entity);
System.out.println("URL: " + post.getURI());
HttpResponse postResponse = client.execute(post, context);
System.out.println(postResponse.getStatusLine());
EntityUtils.consume(postResponse.getEntity());
//Now download the file
HttpGet httpget = new HttpGet("http://url.to.file");
HttpResponse getResponse = client.execute(httpget, context);
System.out.println(getResponse.toString());
System.out.print((postResponse.getEntity().getContent()));
client.getConnectionManager().shutdown();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You are going to have to make an HTTP request for the login page, parse the resulting HTML in the HTTP response stream, and get the token value to use from there. Using a library like jsoup to parse the HTML would be advisable.