How can you send a web request from inside an Android app? - java

Please excuse my lack of knowledge on the topic, but I have very little, if any knowledge of networking, PHP, web requests, and such. Essentially, I want to send a string to a website for logging using $_GET variables. How can I send a string using this method, from inside the app?
(I can't self answer for another 6 hours, but if I COULD, here is what it would look like, with the code in the answer of course. Just didn't wan't to take away from the original question.)
In the end, the code found here worked.
The app sends a request to the web server, which then appends the string in the $_GET variable to a log file! Took a few hours to figure out though. :l

You can use the Apache Commons HttpClient library to make HTTP requests.
HTTP request URIs consist of a protocol scheme, host name, optional port, resource path, optional query, and optional fragment.
HttpGet httpget = new HttpGet(
"http://www.google.com/search?hl=en&q=httpclient&btnG=Google+Search&aq=f&oq=");
Query string can also be generated from individual parameters:
List<NameValuePair> qparams = new ArrayList<NameValuePair>();
qparams.add(new BasicNameValuePair("q", "httpclient"));
qparams.add(new BasicNameValuePair("btnG", "Google Search"));
qparams.add(new BasicNameValuePair("aq", "f"));
qparams.add(new BasicNameValuePair("oq", null));
URI uri = URIUtils.createURI("http", "www.google.com", -1, "/search",
URLEncodedUtils.format(qparams, "UTF-8"), null);
HttpGet httpget = new HttpGet(uri);
System.out.println(httpget.getURI());

wanstein is right, but the URIUtils.createURI is deprecated now (4.2.1), so it is better to use the URIBuilder:
URI uri = new URIBuilder()
.setFragment("http")
.setHost(HOST)
.setPath(path)
.setQuery(URLEncodedUtils.format(qparams, "UTF-8"))
.build();

Related

Cannot send arabic SMS twilio

I want to send an sms that contains arabic letter but when I send the sms. It is being sent like this: ???????
Is there any solution to this problem?
Thanks.
Code:
try{
String twilioSID="AC2be050f87d26aa4b44186c50f6e610e2";
String twilioSecret="abc123";
String urlStr = "https://api.twilio.com/2010-04-01/Accounts/"+twilioSID+"/Messages.json";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urlStr);
String base64EncodedCredentials = "Basic "
+ Base64.encodeToString(
("AC2be050f87d26aa4b44186c50f6e610e2" + ":" + "abc123").getBytes(),
Base64.NO_WRAP);
httppost.setHeader("Authorization", base64EncodedCredentials);
String randomCode2 = UUID.randomUUID().toString().substring(0, 5);
String getmob = getIntent().getStringExtra("mob");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("From", "+1334254136528"));
nameValuePairs.add(new BasicNameValuePair("To", getmob));
nameValuePairs.add(new BasicNameValuePair("Body", "كود السحب على الهدية \n" +
"("+randomCode2+")\n" +
"احتفظ بيه"));
try {
httppost.setEntity(new UrlEncodedFormEntity(
nameValuePairs));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Twilio developer evangelist here.
There are a few things I need to tell you here.
First, please never share your Auth Token publicly. With your Account SID and Auth Token a malicious user could abuse your account. I recommend you immediately change your Auth Token to avoid any attacks.
Next up, you have tagged this Android, so I assume you are doing this in an Android application. You should not make calls directly to the Twilio API from an Android application. This is because to do so you need to include your Auth Token. In this case a malicious user could decompile your Android app and extract your Auth Token and use it to abuse your account. Instead, you should build a server application that can store your credentials and make requests to the Twilio API. Here's a blog post on how to send an SMS from Android with Twilio.
Finally, for when you come to build your server side integration to Twilio, you are using the wrong API endpoint. The URL you build up is:
String urlStr = "https://"+twilioSID+":"+twilioSecret+"#api.twilio.com/2010-04-01/Accounts/"+twilioSID+"/SMS/Messages";
This is using the very old and deprecated /SMS/Messages endpoint. Instead, you should be using the more recent Messages resource, with a URL like this:
https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Messages.json
The /SMS/Messages endpoint did not handle characters outside of ASCII, but the Messages resource can handle any unicode characters.
Since you will be building a server-side integration, I can recommend that you use one of the Twilio helper libraries which make it easier to make requests to the right resource.

Post to SharePoint 2013 from Java

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)

Query parameters sent with HttpPut Request not being read properly

I am trying make an HttpPut Request to the server and send some parameters with it, but however I think that the parameters are not being detected due to which the server send an error message.
My Code is:
URI url = new URI("http://myurl.com/something/something");
HttpClient client = new DefaultHttpClient();
HttpPut hput = new HttpPut(utl);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("id",URLEncoder.encode(ppid,"UTF-8")));
pairs.add(new BasicNameValuePair("name",URLEncoder.encode(netid,"UTF-8")));
hput.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse res = client.execute(hput);
System.out.println(res.getStatusLine);
It says, the PUT method is not supported by the server but the server does support it.
Tried to do a lot research but wasn't successful as most of the posts were just for POST and GET.
Any help would be greatly appreciated.
Thanks.
Most of the servers PUT and DELETE methods are disabled default. Only GET/POST are enabled.

Base64 Encoding Basic Authentication Header Apache HTTP Client

Two related questions, I'm using Apache HTTP Client 4.x API. myHttpPost is an instance of HttpPost and myHttpClient is an instance of HttpClient. I'm trying to send a request using basic authentication. So I have a HttpClient and create a HttpPost.
The 'brute force' way of setting a basic authentication header seems to be to set it in the HttpPost header.
String encoding = Base64Encoder.encode("username" + ":" + "password");
myHttpPost.setHeader("Authorization", "Basic " + encoding);
The example above came from another stack overflow question (can't find link to it now). In relation to the Base64Encoder class - which package would I find it in or where would I download it from?
Main question - I was hoping to do basic authentication in a more aesthetic manner using the code below:
myHttpClient.getCredentialsProvider().setCredentials(
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthPolicy.BASIC),
new UsernamePasswordCredentials("username", "password")
);
But this doesn't seem to work. So is the first example above the right way to do basic authentication with Apache HTTP Client 4.0? Or is there a cleaner/simpler way.
In relation to the Base64Encoder class - which package would I find it
in or where would I download it from?
Base64Encoder can come from various places, I couldn't find something that matches with your static encode method.
As for Credentials, you need to set scheme to Basic on your AuthScope, like so:
myHttpClient.getCredentialsProvider().setCredentials(
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, "basic"),
new UsernamePasswordCredentials("username", "password")
);
or
myHttpClient.getCredentialsProvider().setCredentials(
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthPolicy.BASIC),
new UsernamePasswordCredentials("username", "password")
);
I know this is a really old post. But, just wanted to answer so that others will benefit in future:
If you are using a username which is to be represented using Variable width encoding (http://en.wikipedia.org/wiki/Variable-width_encoding), then make sure that you change the encoding used to form the bytes for (username:password) as follows:
HttpParams params = new BasicHttpParams();
params.setParameter(AuthPNames.CREDENTIAL_CHARSET, HTTP.UTF_8);
By default, the encoding used is HttpProtocolParams.HTTP_ELEMENT_CHARSET.
HttpClient does not attempt to authenticate with the origin or proxy server unless explicitly challenged. I suspect you would like HttpClient to authenticate preemptively. While the preemptive authentication is disabled per default (and I personally would discourage its application outside secure or internal networks) one can force the preemptive authentication using example below
http://hc.apache.org/httpcomponents-client-ga/httpclient/examples/org/apache/http/examples/client/ClientPreemptiveBasicAuthentication.java
I tried out the solution suggested in http://hc.apache.org/httpcomponents-client-ga/httpclient/examples/org/apache/http/examples/client/ClientPreemptiveBasicAuthentication.java and it works for Base64 Encoding Basic Authentication.
I guess the
// Create AuthCache instance
AuthCache authCache = new BasicAuthCache();
// Generate BASIC scheme object and add it to the local
// auth cache
BasicScheme basicAuth = new BasicScheme();
authCache.put(target, basicAuth);
// Add AuthCache to the execution context
HttpClientContext localContext = HttpClientContext.create();
localContext.setAuthCache(authCache);
makes the miracle :)
as without this i always receive "401 Unauthorized" HTTP response

Using HTTP Post on an android device to put data on google app engine's blob store

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.

Categories

Resources