I have a java program that contains a username and passwords (strings) and an ArrayList of objects with 4 attributes (long, int, int int) and I want to pass these 3 things to a WebService (that I have yet to make). My host is Bluehost and it's a shared server so I won't have Java available server side it will need to be in PHP.
What is the best way of connecting to the webservice and passing this into php?
EDIT.
OK so I now have something like this:
public void upload(ArrayList<MyObject> myList) throws Exception{
//HTTP POST Service
try{
HttpClient httpclient = HttpClientBuilder.create().build();
URI uri = new URIBuilder()
.setScheme("http")
.setHost("www.myHost.com")
.setPath("/myWebservice.php")
.setUserInfo(userID, password)
.build();
HttpPost httppost = new HttpPost(uri);
httpclient.execute(httppost);
}catch (Exception e) {
e.printStackTrace();
}
}
But I'm still not sure how I can pass the ArrayList in a way that I'll be able to receive and split it into it's components on the PHP side?
You can use an HTTP client e.g. this one.
http://hc.apache.org/httpcomponents-client-ga/tutorial/html/index.html
and send a GET/POST request to your WebService.
Related
I've tried to connect to our SharePoint and POST some data to a list.
A user can interact with a Web-App and send some Information. These data will be send to a Java-Web-Interface running on a tomcat. The Java-Code should connect to our SharePoint and post the data in the list. Today, I read a lot of tutorials and ressources on the web... Most of them are deprecated ore discuss lightly different situations! SO! My mind whispered: "Go on and visit stackoverflow." And here I am, asking this question:
The Situation is described above. I call a web-Interface vie JS (angularJS) and pass an E-Mail-Adress which the user enters in the front-end. Here it goes in:
#Path("webservice")
public class SetEmail {
#POST
#Path("/SetEmail")
#Consumes(MediaType.APPLICATION_JSON + ";charset=UTF-8")
#Produces("text/plain")
public String addItem(String incoming) throws ClientProtocolException, IOException, AuthenticationException{
String result = "error";
JSONObject jsonObj = new JSONObject(incoming);
String listName = "Leads";
String username = "...";
char[] password= new char[]{'...', '...', ...};
String website = "...";
Now, after all I read, I have to get the DigestValue from SharePoint, because I want to make a POST-Request:
//Get the Digestvalue.
CredentialsProvider provider = new BasicCredentialsProvider();
provider.setCredentials(AuthScope.ANY, new NTCredentials(username, password.toString(), "http://...", "https://..."));
HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
HttpPost httpPost = new HttpPost(website + "_api/contextinfo");
httpPost.addHeader("Accept", "application/json;odata=verbose");
httpPost.addHeader("content-type", "application/json;odata=verbose");
httpPost.addHeader("X-ClientService-ClientTag", "SDK-JAVA");
HttpResponse response = client.execute(httpPost);
byte[] content = EntityUtils.toByteArray(response.getEntity());
String jsonString = new String(content, "UTF-8");
System.out.println(response);
JSONObject json = new JSONObject(jsonString);
String FormDigestValue = json.getJSONObject("d").getJSONObject("GetContextWebInformation").getString("FormDigestValue");
After getting the Digest, I am able to execute the actual request:
//POST the data.
CloseableHttpClient client2 = HttpClients.createDefault();
HttpPost httpPost2 = new HttpPost(website + "_api/web/lists/GetByTitle(" + listName + ")");
httpPost2.setEntity(new StringEntity("test post"));
NTCredentials creds = new NTCredentials(username, password.toString(), "http://...", "https://...");
httpPost2.addHeader(new BasicScheme().authenticate(creds, httpPost2, null));
httpPost2.addHeader("X-RequestDigest", FormDigestValue);
httpPost2.addHeader("Accept", "application/json;odata=verbose");
httpPost2.addHeader("Content-Type", "application/json;odata=verbose");
CloseableHttpResponse response2 = client2.execute(httpPost2);
System.out.println(response2);
client2.close();
}
}
I know this isn't the most beautiful Code and yes, I am not an Java expert. My Problems are:
I don't know weather all of these code-Fragments are up to date or
weather I am using deprecated ones. Perhaps someone is able to
enlighten me.
I am using HttpClient from Apache. To me it looked like the most
usable library. Is that right?
Everytime I execute the Action on the front-end and my Code starts
running, I am getting an HTTP 401 Unauthorized error. I tried
various Kinds of Code but none worked well.
HttpResponseProxy{HTTP/1.1 401 Unauthorized [Server: Microsoft-IIS/8.0, SPR..
Perhaps someone has the Patience to tell me how to do it. Thank you.
Whoa... you are really trying some black magic here ;) - I would suggest you to get your HTTP POST / GET in a tool like Postman or some other REST tool working and then return to your code.
I don't know exactly what you are trying to achieve, but it might be easier to go via powershell (if you are trying to create a migration script) or JavaScript (if you are on a website).
Be aware that authentication differs in SharePoint online and SharePoint on premise... this is also customizable by your company (you can for example implement forms-based auth as well). Be sure to know what YOUR SharePoint is using. (Or share some more info, so we can help)
I want to upload an image to my server through an android app however I would also like to pass other data along with the image (authentication, intention, etc.).
I have normally been making requests like so:
http://server/script.php?t=authtoken&j_id=12&... etc
However, I assume I cannot simply tack on another query parameter containing the byte array for the image as that would result in a URL with a size on the order of millions of characters.
&image=001101010010110111010001010101010110100101000101010100010... etc
I'm at a loss as to how I should approach this and would appreciate any suggestions. If I am not able to send the data through an http request, how would I handle the incoming data server-side?
Thanks.
Here's how I got it work for those who may find this in the future.
For this example, let's say we want to query the PHP script upload.php on the root of www.server.com with the parameters t=ABC123 and id=12. Along with this request, we also want to upload an image stored in the java.io.File object img. We will also be expecting a response from the server letting us know whether the upload was successful or not.
ANDROID SIDE
On the android side, you will need the following JARs:
apache-mime4j-core-0.7.2.jar
Availabe here and:
httpclient-4.3.1.jar
httpcore-4.3.jar
httpmime-4.3.1.jar
Availabe here.
Here is a snippet on how to make the multipart request and get a response:
public String uploadRequest(String address, File img)
{
HttpParams p = new BasicHttpParams();
p.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
DefaultHttpClient client = new DefaultHttpClient(p);
HttpPost post = new HttpPost(address);
// No need to add regular params as parts. You can if you want or
// you can just tack them onto the URL as usual.
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("image", new FileBody(img));
post.setEntity(builder.build());
return client.execute(post, new ImageUploadResponseHandler()).toString();
}
private class ImageUploadResponseHandler implements ResponseHandler<Object>
{
#Override
public Object handleResponse(HttpResponse response) throws ClientProtocolException, IOException
{
HttpEntity responseEntity = response.getEntity();
return EntityUtils.toString(responseEntity);
}
}
An example of using this method in the code (assume the variable img has already been declared containing the File object of the image you wish to upload):
// Notice regular params can be included in the address
String address = "http://www.server.com/upload.php?t=ABC123&id=12";
String resp = uploadRequest(address, img);
// Handle response
PHP SIDE
For the server-side script, the text params can be accessed normally through PHP's $_REQUEST object:
$token = $_REQUEST['token'];
$id = $_REQUEST['id'];
And the image that was uploaded can accessed by using the information stored in the PHP $_FILES object (See the PHP docs for more info):
$img = $_FILES['img'];
I am using the following code in android to send data to a server through a web service
call.When i am sending small amount of data it is hitting the server.When i am sending large data it is not hitting the server.Simply it is httpClient.execute(httpPost); .But i am not getting any result.What might be the problem
HttpPost httpPost = new HttpPost(url+data);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
if (rsopnse != null)
System.out.println(httpPost.getMethod());
try
{
httpResponse= httpClient.execute(httpPost);
}catch(Exception e)
{
e.printStackTrace();
}
Thanks in advance...
You need to create a List<NameValuePair> for all the parameters that you want to pass in the Request. You should not append your parameters to the URL, which is more of the GET style of making a call.
The examples for HTTP Post are covered in the post here.
I have .net web service that expect JSON object. This web service has method for return token:
public string GetToken(string username, string password)...
This is my site url for direct access (when I field manually id, method and params and paste in browser url I receive response )
http://mysite.com/JsonRPC.aspx?id={0}&method={1}¶ms={2}
On stackoverflow I found way to create and send JSON object in android , here is example:
HttpPost request = new HttpPost(URL);
JSONStringer json = new JSONStringer()
.object()
.key("username").value("username")
.key("password").value("password")
.endObject();
Log.i("json",json.toString());
StringEntity entity = new StringEntity(json.toString());
entity.setContentType("application/json;charset=UTF-8");//text/plain;charset=UTF-8
entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
request.setEntity(entity);
// Send request to WCF service
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
My problem is that I don't know how to call my .net web service. What format should be URL variable , where to specific method name , and how to specific method parameters ?
Please give me code
Thanks
I would use this library.
http://code.google.com/p/android-json-rpc/
There are examples on the website that should be sufficient for you.
I am trying to post data to the Blob Store on google's app engine, this code runs without throwing any exceptions, but on the blobstore end there is no log on the post request at all. The server side stuff works when i post using a form (albeit with mime data). I have allowed my android app to use internet. This is a stab in the dark but if any of you folks might have had an issue like this before perhaps the problem i am having might ring a bell!
public void sendVideo() throws IOException {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.theurliampostingto.com/au813rsadjfaruh);
// Add your data
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("key1", "value1"));
pairs.add(new BasicNameValuePair("key2", "value2"));
httpPost.setEntity(new UrlEncodedFormEntity(pairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httpPost);
}
You can try to intercept the traffic between the emulator and the server i.e. with WireShark to see if the server is responding to your request at all.
Your code looks good for me.